babylon.max.js 4.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. //# sourceMappingURL=babylon.types.js.map
  18. var BABYLON;
  19. (function (BABYLON) {
  20. var KeyboardEventTypes = /** @class */ (function () {
  21. function KeyboardEventTypes() {
  22. }
  23. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  24. get: function () {
  25. return KeyboardEventTypes._KEYDOWN;
  26. },
  27. enumerable: true,
  28. configurable: true
  29. });
  30. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  31. get: function () {
  32. return KeyboardEventTypes._KEYUP;
  33. },
  34. enumerable: true,
  35. configurable: true
  36. });
  37. KeyboardEventTypes._KEYDOWN = 0x01;
  38. KeyboardEventTypes._KEYUP = 0x02;
  39. return KeyboardEventTypes;
  40. }());
  41. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  42. var KeyboardInfo = /** @class */ (function () {
  43. function KeyboardInfo(type, event) {
  44. this.type = type;
  45. this.event = event;
  46. }
  47. return KeyboardInfo;
  48. }());
  49. BABYLON.KeyboardInfo = KeyboardInfo;
  50. /**
  51. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  52. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  53. */
  54. var KeyboardInfoPre = /** @class */ (function (_super) {
  55. __extends(KeyboardInfoPre, _super);
  56. function KeyboardInfoPre(type, event) {
  57. var _this = _super.call(this, type, event) || this;
  58. _this.skipOnPointerObservable = false;
  59. return _this;
  60. }
  61. return KeyboardInfoPre;
  62. }(KeyboardInfo));
  63. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  64. })(BABYLON || (BABYLON = {}));
  65. //# sourceMappingURL=babylon.keyboardEvents.js.map
  66. var BABYLON;
  67. (function (BABYLON) {
  68. var PointerEventTypes = /** @class */ (function () {
  69. function PointerEventTypes() {
  70. }
  71. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  72. get: function () {
  73. return PointerEventTypes._POINTERDOWN;
  74. },
  75. enumerable: true,
  76. configurable: true
  77. });
  78. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  79. get: function () {
  80. return PointerEventTypes._POINTERUP;
  81. },
  82. enumerable: true,
  83. configurable: true
  84. });
  85. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  86. get: function () {
  87. return PointerEventTypes._POINTERMOVE;
  88. },
  89. enumerable: true,
  90. configurable: true
  91. });
  92. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  93. get: function () {
  94. return PointerEventTypes._POINTERWHEEL;
  95. },
  96. enumerable: true,
  97. configurable: true
  98. });
  99. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  100. get: function () {
  101. return PointerEventTypes._POINTERPICK;
  102. },
  103. enumerable: true,
  104. configurable: true
  105. });
  106. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  107. get: function () {
  108. return PointerEventTypes._POINTERTAP;
  109. },
  110. enumerable: true,
  111. configurable: true
  112. });
  113. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  114. get: function () {
  115. return PointerEventTypes._POINTERDOUBLETAP;
  116. },
  117. enumerable: true,
  118. configurable: true
  119. });
  120. PointerEventTypes._POINTERDOWN = 0x01;
  121. PointerEventTypes._POINTERUP = 0x02;
  122. PointerEventTypes._POINTERMOVE = 0x04;
  123. PointerEventTypes._POINTERWHEEL = 0x08;
  124. PointerEventTypes._POINTERPICK = 0x10;
  125. PointerEventTypes._POINTERTAP = 0x20;
  126. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  127. return PointerEventTypes;
  128. }());
  129. BABYLON.PointerEventTypes = PointerEventTypes;
  130. var PointerInfoBase = /** @class */ (function () {
  131. function PointerInfoBase(type, event) {
  132. this.type = type;
  133. this.event = event;
  134. }
  135. return PointerInfoBase;
  136. }());
  137. BABYLON.PointerInfoBase = PointerInfoBase;
  138. /**
  139. * This class is used to store pointer related info for the onPrePointerObservable event.
  140. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  141. */
  142. var PointerInfoPre = /** @class */ (function (_super) {
  143. __extends(PointerInfoPre, _super);
  144. function PointerInfoPre(type, event, localX, localY) {
  145. var _this = _super.call(this, type, event) || this;
  146. _this.skipOnPointerObservable = false;
  147. _this.localPosition = new BABYLON.Vector2(localX, localY);
  148. return _this;
  149. }
  150. return PointerInfoPre;
  151. }(PointerInfoBase));
  152. BABYLON.PointerInfoPre = PointerInfoPre;
  153. /**
  154. * This type contains all the data related to a pointer event in Babylon.js.
  155. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  156. */
  157. var PointerInfo = /** @class */ (function (_super) {
  158. __extends(PointerInfo, _super);
  159. function PointerInfo(type, event, pickInfo) {
  160. var _this = _super.call(this, type, event) || this;
  161. _this.pickInfo = pickInfo;
  162. return _this;
  163. }
  164. return PointerInfo;
  165. }(PointerInfoBase));
  166. BABYLON.PointerInfo = PointerInfo;
  167. })(BABYLON || (BABYLON = {}));
  168. //# sourceMappingURL=babylon.pointerEvents.js.map
  169. var BABYLON;
  170. (function (BABYLON) {
  171. BABYLON.ToGammaSpace = 1 / 2.2;
  172. BABYLON.ToLinearSpace = 2.2;
  173. BABYLON.Epsilon = 0.001;
  174. var Color3 = /** @class */ (function () {
  175. /**
  176. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  177. */
  178. function Color3(r, g, b) {
  179. if (r === void 0) { r = 0; }
  180. if (g === void 0) { g = 0; }
  181. if (b === void 0) { b = 0; }
  182. this.r = r;
  183. this.g = g;
  184. this.b = b;
  185. }
  186. /**
  187. * Returns a string with the Color3 current values.
  188. */
  189. Color3.prototype.toString = function () {
  190. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  191. };
  192. /**
  193. * Returns the string "Color3".
  194. */
  195. Color3.prototype.getClassName = function () {
  196. return "Color3";
  197. };
  198. /**
  199. * Returns the Color3 hash code.
  200. */
  201. Color3.prototype.getHashCode = function () {
  202. var hash = this.r || 0;
  203. hash = (hash * 397) ^ (this.g || 0);
  204. hash = (hash * 397) ^ (this.b || 0);
  205. return hash;
  206. };
  207. // Operators
  208. /**
  209. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  210. * Returns the Color3.
  211. */
  212. Color3.prototype.toArray = function (array, index) {
  213. if (index === undefined) {
  214. index = 0;
  215. }
  216. array[index] = this.r;
  217. array[index + 1] = this.g;
  218. array[index + 2] = this.b;
  219. return this;
  220. };
  221. /**
  222. * Returns a new Color4 object from the current Color3 and the passed alpha.
  223. */
  224. Color3.prototype.toColor4 = function (alpha) {
  225. if (alpha === void 0) { alpha = 1; }
  226. return new Color4(this.r, this.g, this.b, alpha);
  227. };
  228. /**
  229. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  230. */
  231. Color3.prototype.asArray = function () {
  232. var result = new Array();
  233. this.toArray(result, 0);
  234. return result;
  235. };
  236. /**
  237. * Returns the luminance value (float).
  238. */
  239. Color3.prototype.toLuminance = function () {
  240. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  241. };
  242. /**
  243. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  244. * Returns this new object.
  245. */
  246. Color3.prototype.multiply = function (otherColor) {
  247. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  248. };
  249. /**
  250. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  251. * Returns the current Color3.
  252. */
  253. Color3.prototype.multiplyToRef = function (otherColor, result) {
  254. result.r = this.r * otherColor.r;
  255. result.g = this.g * otherColor.g;
  256. result.b = this.b * otherColor.b;
  257. return this;
  258. };
  259. /**
  260. * Boolean : True if the rgb values are equal to the passed ones.
  261. */
  262. Color3.prototype.equals = function (otherColor) {
  263. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  264. };
  265. /**
  266. * Boolean : True if the rgb values are equal to the passed ones.
  267. */
  268. Color3.prototype.equalsFloats = function (r, g, b) {
  269. return this.r === r && this.g === g && this.b === b;
  270. };
  271. /**
  272. * Multiplies in place each rgb value by scale.
  273. * Returns the updated Color3.
  274. */
  275. Color3.prototype.scale = function (scale) {
  276. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  277. };
  278. /**
  279. * Multiplies the rgb values by scale and stores the result into "result".
  280. * Returns the unmodified current Color3.
  281. */
  282. Color3.prototype.scaleToRef = function (scale, result) {
  283. result.r = this.r * scale;
  284. result.g = this.g * scale;
  285. result.b = this.b * scale;
  286. return this;
  287. };
  288. /**
  289. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  290. */
  291. Color3.prototype.add = function (otherColor) {
  292. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  293. };
  294. /**
  295. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  296. * Returns the unmodified current Color3.
  297. */
  298. Color3.prototype.addToRef = function (otherColor, result) {
  299. result.r = this.r + otherColor.r;
  300. result.g = this.g + otherColor.g;
  301. result.b = this.b + otherColor.b;
  302. return this;
  303. };
  304. /**
  305. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  306. */
  307. Color3.prototype.subtract = function (otherColor) {
  308. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  309. };
  310. /**
  311. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  312. * Returns the unmodified current Color3.
  313. */
  314. Color3.prototype.subtractToRef = function (otherColor, result) {
  315. result.r = this.r - otherColor.r;
  316. result.g = this.g - otherColor.g;
  317. result.b = this.b - otherColor.b;
  318. return this;
  319. };
  320. /**
  321. * Returns a new Color3 copied the current one.
  322. */
  323. Color3.prototype.clone = function () {
  324. return new Color3(this.r, this.g, this.b);
  325. };
  326. /**
  327. * Copies the rgb values from the source in the current Color3.
  328. * Returns the updated Color3.
  329. */
  330. Color3.prototype.copyFrom = function (source) {
  331. this.r = source.r;
  332. this.g = source.g;
  333. this.b = source.b;
  334. return this;
  335. };
  336. /**
  337. * Updates the Color3 rgb values from the passed floats.
  338. * Returns the Color3.
  339. */
  340. Color3.prototype.copyFromFloats = function (r, g, b) {
  341. this.r = r;
  342. this.g = g;
  343. this.b = b;
  344. return this;
  345. };
  346. /**
  347. * Updates the Color3 rgb values from the passed floats.
  348. * Returns the Color3.
  349. */
  350. Color3.prototype.set = function (r, g, b) {
  351. return this.copyFromFloats(r, g, b);
  352. };
  353. /**
  354. * Returns the Color3 hexadecimal code as a string.
  355. */
  356. Color3.prototype.toHexString = function () {
  357. var intR = (this.r * 255) | 0;
  358. var intG = (this.g * 255) | 0;
  359. var intB = (this.b * 255) | 0;
  360. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  361. };
  362. /**
  363. * Returns a new Color3 converted to linear space.
  364. */
  365. Color3.prototype.toLinearSpace = function () {
  366. var convertedColor = new Color3();
  367. this.toLinearSpaceToRef(convertedColor);
  368. return convertedColor;
  369. };
  370. /**
  371. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  372. * Returns the unmodified Color3.
  373. */
  374. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  375. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  376. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  377. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  378. return this;
  379. };
  380. /**
  381. * Returns a new Color3 converted to gamma space.
  382. */
  383. Color3.prototype.toGammaSpace = function () {
  384. var convertedColor = new Color3();
  385. this.toGammaSpaceToRef(convertedColor);
  386. return convertedColor;
  387. };
  388. /**
  389. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  390. * Returns the unmodified Color3.
  391. */
  392. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  393. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  394. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  395. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  396. return this;
  397. };
  398. // Statics
  399. /**
  400. * Creates a new Color3 from the string containing valid hexadecimal values.
  401. */
  402. Color3.FromHexString = function (hex) {
  403. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  404. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  405. return new Color3(0, 0, 0);
  406. }
  407. var r = parseInt(hex.substring(1, 3), 16);
  408. var g = parseInt(hex.substring(3, 5), 16);
  409. var b = parseInt(hex.substring(5, 7), 16);
  410. return Color3.FromInts(r, g, b);
  411. };
  412. /**
  413. * Creates a new Vector3 from the startind index of the passed array.
  414. */
  415. Color3.FromArray = function (array, offset) {
  416. if (offset === void 0) { offset = 0; }
  417. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  418. };
  419. /**
  420. * Creates a new Color3 from integer values ( < 256).
  421. */
  422. Color3.FromInts = function (r, g, b) {
  423. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  424. };
  425. /**
  426. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  427. */
  428. Color3.Lerp = function (start, end, amount) {
  429. var r = start.r + ((end.r - start.r) * amount);
  430. var g = start.g + ((end.g - start.g) * amount);
  431. var b = start.b + ((end.b - start.b) * amount);
  432. return new Color3(r, g, b);
  433. };
  434. Color3.Red = function () { return new Color3(1, 0, 0); };
  435. Color3.Green = function () { return new Color3(0, 1, 0); };
  436. Color3.Blue = function () { return new Color3(0, 0, 1); };
  437. Color3.Black = function () { return new Color3(0, 0, 0); };
  438. Color3.White = function () { return new Color3(1, 1, 1); };
  439. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  440. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  441. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  442. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  443. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  444. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  445. return Color3;
  446. }());
  447. BABYLON.Color3 = Color3;
  448. var Color4 = /** @class */ (function () {
  449. /**
  450. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  451. */
  452. function Color4(r, g, b, a) {
  453. if (r === void 0) { r = 0; }
  454. if (g === void 0) { g = 0; }
  455. if (b === void 0) { b = 0; }
  456. if (a === void 0) { a = 1; }
  457. this.r = r;
  458. this.g = g;
  459. this.b = b;
  460. this.a = a;
  461. }
  462. // Operators
  463. /**
  464. * Adds in place the passed Color4 values to the current Color4.
  465. * Returns the updated Color4.
  466. */
  467. Color4.prototype.addInPlace = function (right) {
  468. this.r += right.r;
  469. this.g += right.g;
  470. this.b += right.b;
  471. this.a += right.a;
  472. return this;
  473. };
  474. /**
  475. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  476. */
  477. Color4.prototype.asArray = function () {
  478. var result = new Array();
  479. this.toArray(result, 0);
  480. return result;
  481. };
  482. /**
  483. * Stores from the starting index in the passed array the Color4 successive values.
  484. * Returns the Color4.
  485. */
  486. Color4.prototype.toArray = function (array, index) {
  487. if (index === undefined) {
  488. index = 0;
  489. }
  490. array[index] = this.r;
  491. array[index + 1] = this.g;
  492. array[index + 2] = this.b;
  493. array[index + 3] = this.a;
  494. return this;
  495. };
  496. /**
  497. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  498. */
  499. Color4.prototype.add = function (right) {
  500. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  501. };
  502. /**
  503. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  504. */
  505. Color4.prototype.subtract = function (right) {
  506. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  507. };
  508. /**
  509. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  510. * Returns the Color4.
  511. */
  512. Color4.prototype.subtractToRef = function (right, result) {
  513. result.r = this.r - right.r;
  514. result.g = this.g - right.g;
  515. result.b = this.b - right.b;
  516. result.a = this.a - right.a;
  517. return this;
  518. };
  519. /**
  520. * Creates a new Color4 with the current Color4 values multiplied by scale.
  521. */
  522. Color4.prototype.scale = function (scale) {
  523. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  524. };
  525. /**
  526. * Multiplies the current Color4 values by scale and stores the result in "result".
  527. * Returns the Color4.
  528. */
  529. Color4.prototype.scaleToRef = function (scale, result) {
  530. result.r = this.r * scale;
  531. result.g = this.g * scale;
  532. result.b = this.b * scale;
  533. result.a = this.a * scale;
  534. return this;
  535. };
  536. /**
  537. * Multipy an RGBA Color4 value by another and return a new Color4 object
  538. * @param color The Color4 (RGBA) value to multiply by
  539. * @returns A new Color4.
  540. */
  541. Color4.prototype.multiply = function (color) {
  542. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  543. };
  544. /**
  545. * Multipy an RGBA Color4 value by another and push the result in a reference value
  546. * @param color The Color4 (RGBA) value to multiply by
  547. * @param result The Color4 (RGBA) to fill the result in
  548. * @returns the result Color4.
  549. */
  550. Color4.prototype.multiplyToRef = function (color, result) {
  551. result.r = this.r * color.r;
  552. result.g = this.g * color.g;
  553. result.b = this.b * color.b;
  554. result.a = this.a * color.a;
  555. return result;
  556. };
  557. /**
  558. * Returns a string with the Color4 values.
  559. */
  560. Color4.prototype.toString = function () {
  561. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  562. };
  563. /**
  564. * Returns the string "Color4"
  565. */
  566. Color4.prototype.getClassName = function () {
  567. return "Color4";
  568. };
  569. /**
  570. * Return the Color4 hash code as a number.
  571. */
  572. Color4.prototype.getHashCode = function () {
  573. var hash = this.r || 0;
  574. hash = (hash * 397) ^ (this.g || 0);
  575. hash = (hash * 397) ^ (this.b || 0);
  576. hash = (hash * 397) ^ (this.a || 0);
  577. return hash;
  578. };
  579. /**
  580. * Creates a new Color4 copied from the current one.
  581. */
  582. Color4.prototype.clone = function () {
  583. return new Color4(this.r, this.g, this.b, this.a);
  584. };
  585. /**
  586. * Copies the passed Color4 values into the current one.
  587. * Returns the updated Color4.
  588. */
  589. Color4.prototype.copyFrom = function (source) {
  590. this.r = source.r;
  591. this.g = source.g;
  592. this.b = source.b;
  593. this.a = source.a;
  594. return this;
  595. };
  596. /**
  597. * Copies the passed float values into the current one.
  598. * Returns the updated Color4.
  599. */
  600. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  601. this.r = r;
  602. this.g = g;
  603. this.b = b;
  604. this.a = a;
  605. return this;
  606. };
  607. /**
  608. * Copies the passed float values into the current one.
  609. * Returns the updated Color4.
  610. */
  611. Color4.prototype.set = function (r, g, b, a) {
  612. return this.copyFromFloats(r, g, b, a);
  613. };
  614. /**
  615. * Returns a string containing the hexadecimal Color4 code.
  616. */
  617. Color4.prototype.toHexString = function () {
  618. var intR = (this.r * 255) | 0;
  619. var intG = (this.g * 255) | 0;
  620. var intB = (this.b * 255) | 0;
  621. var intA = (this.a * 255) | 0;
  622. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  623. };
  624. /**
  625. * Returns a new Color4 converted to linear space.
  626. */
  627. Color4.prototype.toLinearSpace = function () {
  628. var convertedColor = new Color4();
  629. this.toLinearSpaceToRef(convertedColor);
  630. return convertedColor;
  631. };
  632. /**
  633. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  634. * Returns the unmodified Color4.
  635. */
  636. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  637. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  638. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  639. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  640. convertedColor.a = this.a;
  641. return this;
  642. };
  643. /**
  644. * Returns a new Color4 converted to gamma space.
  645. */
  646. Color4.prototype.toGammaSpace = function () {
  647. var convertedColor = new Color4();
  648. this.toGammaSpaceToRef(convertedColor);
  649. return convertedColor;
  650. };
  651. /**
  652. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  653. * Returns the unmodified Color4.
  654. */
  655. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  656. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  657. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  658. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  659. convertedColor.a = this.a;
  660. return this;
  661. };
  662. // Statics
  663. /**
  664. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  665. */
  666. Color4.FromHexString = function (hex) {
  667. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  668. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  669. return new Color4(0.0, 0.0, 0.0, 0.0);
  670. }
  671. var r = parseInt(hex.substring(1, 3), 16);
  672. var g = parseInt(hex.substring(3, 5), 16);
  673. var b = parseInt(hex.substring(5, 7), 16);
  674. var a = parseInt(hex.substring(7, 9), 16);
  675. return Color4.FromInts(r, g, b, a);
  676. };
  677. /**
  678. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  679. */
  680. Color4.Lerp = function (left, right, amount) {
  681. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  682. Color4.LerpToRef(left, right, amount, result);
  683. return result;
  684. };
  685. /**
  686. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  687. */
  688. Color4.LerpToRef = function (left, right, amount, result) {
  689. result.r = left.r + (right.r - left.r) * amount;
  690. result.g = left.g + (right.g - left.g) * amount;
  691. result.b = left.b + (right.b - left.b) * amount;
  692. result.a = left.a + (right.a - left.a) * amount;
  693. };
  694. /**
  695. * Creates a new Color4 from the starting index element of the passed array.
  696. */
  697. Color4.FromArray = function (array, offset) {
  698. if (offset === void 0) { offset = 0; }
  699. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  700. };
  701. /**
  702. * Creates a new Color4 from the passed integers ( < 256 ).
  703. */
  704. Color4.FromInts = function (r, g, b, a) {
  705. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  706. };
  707. Color4.CheckColors4 = function (colors, count) {
  708. // Check if color3 was used
  709. if (colors.length === count * 3) {
  710. var colors4 = [];
  711. for (var index = 0; index < colors.length; index += 3) {
  712. var newIndex = (index / 3) * 4;
  713. colors4[newIndex] = colors[index];
  714. colors4[newIndex + 1] = colors[index + 1];
  715. colors4[newIndex + 2] = colors[index + 2];
  716. colors4[newIndex + 3] = 1.0;
  717. }
  718. return colors4;
  719. }
  720. return colors;
  721. };
  722. return Color4;
  723. }());
  724. BABYLON.Color4 = Color4;
  725. var Vector2 = /** @class */ (function () {
  726. /**
  727. * Creates a new Vector2 from the passed x and y coordinates.
  728. */
  729. function Vector2(x, y) {
  730. this.x = x;
  731. this.y = y;
  732. }
  733. /**
  734. * Returns a string with the Vector2 coordinates.
  735. */
  736. Vector2.prototype.toString = function () {
  737. return "{X: " + this.x + " Y:" + this.y + "}";
  738. };
  739. /**
  740. * Returns the string "Vector2"
  741. */
  742. Vector2.prototype.getClassName = function () {
  743. return "Vector2";
  744. };
  745. /**
  746. * Returns the Vector2 hash code as a number.
  747. */
  748. Vector2.prototype.getHashCode = function () {
  749. var hash = this.x || 0;
  750. hash = (hash * 397) ^ (this.y || 0);
  751. return hash;
  752. };
  753. // Operators
  754. /**
  755. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  756. * Returns the Vector2.
  757. */
  758. Vector2.prototype.toArray = function (array, index) {
  759. if (index === void 0) { index = 0; }
  760. array[index] = this.x;
  761. array[index + 1] = this.y;
  762. return this;
  763. };
  764. /**
  765. * Returns a new array with 2 elements : the Vector2 coordinates.
  766. */
  767. Vector2.prototype.asArray = function () {
  768. var result = new Array();
  769. this.toArray(result, 0);
  770. return result;
  771. };
  772. /**
  773. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  774. * Returns the updated Vector2.
  775. */
  776. Vector2.prototype.copyFrom = function (source) {
  777. this.x = source.x;
  778. this.y = source.y;
  779. return this;
  780. };
  781. /**
  782. * Sets the Vector2 coordinates with the passed floats.
  783. * Returns the updated Vector2.
  784. */
  785. Vector2.prototype.copyFromFloats = function (x, y) {
  786. this.x = x;
  787. this.y = y;
  788. return this;
  789. };
  790. /**
  791. * Sets the Vector2 coordinates with the passed floats.
  792. * Returns the updated Vector2.
  793. */
  794. Vector2.prototype.set = function (x, y) {
  795. return this.copyFromFloats(x, y);
  796. };
  797. /**
  798. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  799. */
  800. Vector2.prototype.add = function (otherVector) {
  801. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  802. };
  803. /**
  804. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  805. * Returns the Vector2.
  806. */
  807. Vector2.prototype.addToRef = function (otherVector, result) {
  808. result.x = this.x + otherVector.x;
  809. result.y = this.y + otherVector.y;
  810. return this;
  811. };
  812. /**
  813. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  814. * Returns the updated Vector2.
  815. */
  816. Vector2.prototype.addInPlace = function (otherVector) {
  817. this.x += otherVector.x;
  818. this.y += otherVector.y;
  819. return this;
  820. };
  821. /**
  822. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  823. */
  824. Vector2.prototype.addVector3 = function (otherVector) {
  825. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  826. };
  827. /**
  828. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  829. */
  830. Vector2.prototype.subtract = function (otherVector) {
  831. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  832. };
  833. /**
  834. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  835. * Returns the Vector2.
  836. */
  837. Vector2.prototype.subtractToRef = function (otherVector, result) {
  838. result.x = this.x - otherVector.x;
  839. result.y = this.y - otherVector.y;
  840. return this;
  841. };
  842. /**
  843. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  844. * Returns the updated Vector2.
  845. */
  846. Vector2.prototype.subtractInPlace = function (otherVector) {
  847. this.x -= otherVector.x;
  848. this.y -= otherVector.y;
  849. return this;
  850. };
  851. /**
  852. * Multiplies in place the current Vector2 coordinates by the passed ones.
  853. * Returns the updated Vector2.
  854. */
  855. Vector2.prototype.multiplyInPlace = function (otherVector) {
  856. this.x *= otherVector.x;
  857. this.y *= otherVector.y;
  858. return this;
  859. };
  860. /**
  861. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  862. */
  863. Vector2.prototype.multiply = function (otherVector) {
  864. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  865. };
  866. /**
  867. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  868. * Returns the Vector2.
  869. */
  870. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  871. result.x = this.x * otherVector.x;
  872. result.y = this.y * otherVector.y;
  873. return this;
  874. };
  875. /**
  876. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  877. */
  878. Vector2.prototype.multiplyByFloats = function (x, y) {
  879. return new Vector2(this.x * x, this.y * y);
  880. };
  881. /**
  882. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  883. */
  884. Vector2.prototype.divide = function (otherVector) {
  885. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  886. };
  887. /**
  888. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  889. * Returns the Vector2.
  890. */
  891. Vector2.prototype.divideToRef = function (otherVector, result) {
  892. result.x = this.x / otherVector.x;
  893. result.y = this.y / otherVector.y;
  894. return this;
  895. };
  896. /**
  897. * Returns a new Vector2 with current Vector2 negated coordinates.
  898. */
  899. Vector2.prototype.negate = function () {
  900. return new Vector2(-this.x, -this.y);
  901. };
  902. /**
  903. * Multiply the Vector2 coordinates by scale.
  904. * Returns the updated Vector2.
  905. */
  906. Vector2.prototype.scaleInPlace = function (scale) {
  907. this.x *= scale;
  908. this.y *= scale;
  909. return this;
  910. };
  911. /**
  912. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  913. */
  914. Vector2.prototype.scale = function (scale) {
  915. return new Vector2(this.x * scale, this.y * scale);
  916. };
  917. /**
  918. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  919. */
  920. Vector2.prototype.equals = function (otherVector) {
  921. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  922. };
  923. /**
  924. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  925. */
  926. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  927. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  928. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  929. };
  930. // Properties
  931. /**
  932. * Returns the vector length (float).
  933. */
  934. Vector2.prototype.length = function () {
  935. return Math.sqrt(this.x * this.x + this.y * this.y);
  936. };
  937. /**
  938. * Returns the vector squared length (float);
  939. */
  940. Vector2.prototype.lengthSquared = function () {
  941. return (this.x * this.x + this.y * this.y);
  942. };
  943. // Methods
  944. /**
  945. * Normalize the vector.
  946. * Returns the updated Vector2.
  947. */
  948. Vector2.prototype.normalize = function () {
  949. var len = this.length();
  950. if (len === 0)
  951. return this;
  952. var num = 1.0 / len;
  953. this.x *= num;
  954. this.y *= num;
  955. return this;
  956. };
  957. /**
  958. * Returns a new Vector2 copied from the Vector2.
  959. */
  960. Vector2.prototype.clone = function () {
  961. return new Vector2(this.x, this.y);
  962. };
  963. // Statics
  964. /**
  965. * Returns a new Vector2(0, 0)
  966. */
  967. Vector2.Zero = function () {
  968. return new Vector2(0, 0);
  969. };
  970. /**
  971. * Returns a new Vector2(1, 1)
  972. */
  973. Vector2.One = function () {
  974. return new Vector2(1, 1);
  975. };
  976. /**
  977. * Returns a new Vector2 set from the passed index element of the passed array.
  978. */
  979. Vector2.FromArray = function (array, offset) {
  980. if (offset === void 0) { offset = 0; }
  981. return new Vector2(array[offset], array[offset + 1]);
  982. };
  983. /**
  984. * Sets "result" from the passed index element of the passed array.
  985. */
  986. Vector2.FromArrayToRef = function (array, offset, result) {
  987. result.x = array[offset];
  988. result.y = array[offset + 1];
  989. };
  990. /**
  991. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  992. */
  993. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  994. var squared = amount * amount;
  995. var cubed = amount * squared;
  996. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  997. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  998. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  999. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1000. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1001. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1002. return new Vector2(x, y);
  1003. };
  1004. /**
  1005. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  1006. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1007. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1008. */
  1009. Vector2.Clamp = function (value, min, max) {
  1010. var x = value.x;
  1011. x = (x > max.x) ? max.x : x;
  1012. x = (x < min.x) ? min.x : x;
  1013. var y = value.y;
  1014. y = (y > max.y) ? max.y : y;
  1015. y = (y < min.y) ? min.y : y;
  1016. return new Vector2(x, y);
  1017. };
  1018. /**
  1019. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1020. */
  1021. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1022. var squared = amount * amount;
  1023. var cubed = amount * squared;
  1024. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1025. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1026. var part3 = (cubed - (2.0 * squared)) + amount;
  1027. var part4 = cubed - squared;
  1028. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1029. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1030. return new Vector2(x, y);
  1031. };
  1032. /**
  1033. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1034. */
  1035. Vector2.Lerp = function (start, end, amount) {
  1036. var x = start.x + ((end.x - start.x) * amount);
  1037. var y = start.y + ((end.y - start.y) * amount);
  1038. return new Vector2(x, y);
  1039. };
  1040. /**
  1041. * Returns the dot product (float) of the vector "left" and the vector "right".
  1042. */
  1043. Vector2.Dot = function (left, right) {
  1044. return left.x * right.x + left.y * right.y;
  1045. };
  1046. /**
  1047. * Returns a new Vector2 equal to the normalized passed vector.
  1048. */
  1049. Vector2.Normalize = function (vector) {
  1050. var newVector = vector.clone();
  1051. newVector.normalize();
  1052. return newVector;
  1053. };
  1054. /**
  1055. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1056. */
  1057. Vector2.Minimize = function (left, right) {
  1058. var x = (left.x < right.x) ? left.x : right.x;
  1059. var y = (left.y < right.y) ? left.y : right.y;
  1060. return new Vector2(x, y);
  1061. };
  1062. /**
  1063. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1064. */
  1065. Vector2.Maximize = function (left, right) {
  1066. var x = (left.x > right.x) ? left.x : right.x;
  1067. var y = (left.y > right.y) ? left.y : right.y;
  1068. return new Vector2(x, y);
  1069. };
  1070. /**
  1071. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1072. */
  1073. Vector2.Transform = function (vector, transformation) {
  1074. var r = Vector2.Zero();
  1075. Vector2.TransformToRef(vector, transformation, r);
  1076. return r;
  1077. };
  1078. /**
  1079. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1080. */
  1081. Vector2.TransformToRef = function (vector, transformation, result) {
  1082. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1083. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1084. result.x = x;
  1085. result.y = y;
  1086. };
  1087. /**
  1088. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1089. */
  1090. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1091. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1092. var sign = a < 0 ? -1 : 1;
  1093. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1094. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1095. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1096. };
  1097. /**
  1098. * Returns the distance (float) between the vectors "value1" and "value2".
  1099. */
  1100. Vector2.Distance = function (value1, value2) {
  1101. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1102. };
  1103. /**
  1104. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1105. */
  1106. Vector2.DistanceSquared = function (value1, value2) {
  1107. var x = value1.x - value2.x;
  1108. var y = value1.y - value2.y;
  1109. return (x * x) + (y * y);
  1110. };
  1111. /**
  1112. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1113. */
  1114. Vector2.Center = function (value1, value2) {
  1115. var center = value1.add(value2);
  1116. center.scaleInPlace(0.5);
  1117. return center;
  1118. };
  1119. /**
  1120. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1121. */
  1122. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1123. var l2 = Vector2.DistanceSquared(segA, segB);
  1124. if (l2 === 0.0) {
  1125. return Vector2.Distance(p, segA);
  1126. }
  1127. var v = segB.subtract(segA);
  1128. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1129. var proj = segA.add(v.multiplyByFloats(t, t));
  1130. return Vector2.Distance(p, proj);
  1131. };
  1132. return Vector2;
  1133. }());
  1134. BABYLON.Vector2 = Vector2;
  1135. var Vector3 = /** @class */ (function () {
  1136. /**
  1137. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1138. * A Vector3 is the main object used in 3D geometry.
  1139. * It can represent etiher the coordinates of a point the space, either a direction.
  1140. */
  1141. function Vector3(x, y, z) {
  1142. this.x = x;
  1143. this.y = y;
  1144. this.z = z;
  1145. }
  1146. /**
  1147. * Returns a string with the Vector3 coordinates.
  1148. */
  1149. Vector3.prototype.toString = function () {
  1150. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1151. };
  1152. /**
  1153. * Returns the string "Vector3"
  1154. */
  1155. Vector3.prototype.getClassName = function () {
  1156. return "Vector3";
  1157. };
  1158. /**
  1159. * Returns the Vector hash code.
  1160. */
  1161. Vector3.prototype.getHashCode = function () {
  1162. var hash = this.x || 0;
  1163. hash = (hash * 397) ^ (this.y || 0);
  1164. hash = (hash * 397) ^ (this.z || 0);
  1165. return hash;
  1166. };
  1167. // Operators
  1168. /**
  1169. * Returns a new array with three elements : the coordinates the Vector3.
  1170. */
  1171. Vector3.prototype.asArray = function () {
  1172. var result = [];
  1173. this.toArray(result, 0);
  1174. return result;
  1175. };
  1176. /**
  1177. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1178. * Returns the Vector3.
  1179. */
  1180. Vector3.prototype.toArray = function (array, index) {
  1181. if (index === void 0) { index = 0; }
  1182. array[index] = this.x;
  1183. array[index + 1] = this.y;
  1184. array[index + 2] = this.z;
  1185. return this;
  1186. };
  1187. /**
  1188. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1189. */
  1190. Vector3.prototype.toQuaternion = function () {
  1191. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1192. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1193. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1194. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1195. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1196. var cosy = Math.cos(this.y * 0.5);
  1197. var siny = Math.sin(this.y * 0.5);
  1198. result.x = coszMinusx * siny;
  1199. result.y = -sinzMinusx * siny;
  1200. result.z = sinxPlusz * cosy;
  1201. result.w = cosxPlusz * cosy;
  1202. return result;
  1203. };
  1204. /**
  1205. * Adds the passed vector to the current Vector3.
  1206. * Returns the updated Vector3.
  1207. */
  1208. Vector3.prototype.addInPlace = function (otherVector) {
  1209. this.x += otherVector.x;
  1210. this.y += otherVector.y;
  1211. this.z += otherVector.z;
  1212. return this;
  1213. };
  1214. /**
  1215. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1216. */
  1217. Vector3.prototype.add = function (otherVector) {
  1218. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1219. };
  1220. /**
  1221. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1222. * Returns the current Vector3.
  1223. */
  1224. Vector3.prototype.addToRef = function (otherVector, result) {
  1225. result.x = this.x + otherVector.x;
  1226. result.y = this.y + otherVector.y;
  1227. result.z = this.z + otherVector.z;
  1228. return this;
  1229. };
  1230. /**
  1231. * Subtract the passed vector from the current Vector3.
  1232. * Returns the updated Vector3.
  1233. */
  1234. Vector3.prototype.subtractInPlace = function (otherVector) {
  1235. this.x -= otherVector.x;
  1236. this.y -= otherVector.y;
  1237. this.z -= otherVector.z;
  1238. return this;
  1239. };
  1240. /**
  1241. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1242. */
  1243. Vector3.prototype.subtract = function (otherVector) {
  1244. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1245. };
  1246. /**
  1247. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1248. * Returns the current Vector3.
  1249. */
  1250. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1251. result.x = this.x - otherVector.x;
  1252. result.y = this.y - otherVector.y;
  1253. result.z = this.z - otherVector.z;
  1254. return this;
  1255. };
  1256. /**
  1257. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1258. */
  1259. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1260. return new Vector3(this.x - x, this.y - y, this.z - z);
  1261. };
  1262. /**
  1263. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1264. * Returns the current Vector3.
  1265. */
  1266. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1267. result.x = this.x - x;
  1268. result.y = this.y - y;
  1269. result.z = this.z - z;
  1270. return this;
  1271. };
  1272. /**
  1273. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1274. */
  1275. Vector3.prototype.negate = function () {
  1276. return new Vector3(-this.x, -this.y, -this.z);
  1277. };
  1278. /**
  1279. * Multiplies the Vector3 coordinates by the float "scale".
  1280. * Returns the updated Vector3.
  1281. */
  1282. Vector3.prototype.scaleInPlace = function (scale) {
  1283. this.x *= scale;
  1284. this.y *= scale;
  1285. this.z *= scale;
  1286. return this;
  1287. };
  1288. /**
  1289. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1290. */
  1291. Vector3.prototype.scale = function (scale) {
  1292. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1293. };
  1294. /**
  1295. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1296. * Returns the current Vector3.
  1297. */
  1298. Vector3.prototype.scaleToRef = function (scale, result) {
  1299. result.x = this.x * scale;
  1300. result.y = this.y * scale;
  1301. result.z = this.z * scale;
  1302. return this;
  1303. };
  1304. /**
  1305. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1306. */
  1307. Vector3.prototype.equals = function (otherVector) {
  1308. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1309. };
  1310. /**
  1311. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1312. */
  1313. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1314. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1315. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  1316. };
  1317. /**
  1318. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1319. */
  1320. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1321. return this.x === x && this.y === y && this.z === z;
  1322. };
  1323. /**
  1324. * Muliplies the current Vector3 coordinates by the passed ones.
  1325. * Returns the updated Vector3.
  1326. */
  1327. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1328. this.x *= otherVector.x;
  1329. this.y *= otherVector.y;
  1330. this.z *= otherVector.z;
  1331. return this;
  1332. };
  1333. /**
  1334. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1335. */
  1336. Vector3.prototype.multiply = function (otherVector) {
  1337. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1338. };
  1339. /**
  1340. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1341. * Returns the current Vector3.
  1342. */
  1343. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1344. result.x = this.x * otherVector.x;
  1345. result.y = this.y * otherVector.y;
  1346. result.z = this.z * otherVector.z;
  1347. return this;
  1348. };
  1349. /**
  1350. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1351. */
  1352. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1353. return new Vector3(this.x * x, this.y * y, this.z * z);
  1354. };
  1355. /**
  1356. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1357. */
  1358. Vector3.prototype.divide = function (otherVector) {
  1359. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1360. };
  1361. /**
  1362. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1363. * Returns the current Vector3.
  1364. */
  1365. Vector3.prototype.divideToRef = function (otherVector, result) {
  1366. result.x = this.x / otherVector.x;
  1367. result.y = this.y / otherVector.y;
  1368. result.z = this.z / otherVector.z;
  1369. return this;
  1370. };
  1371. /**
  1372. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1373. * Returns the updated Vector3.
  1374. */
  1375. Vector3.prototype.MinimizeInPlace = function (other) {
  1376. if (other.x < this.x)
  1377. this.x = other.x;
  1378. if (other.y < this.y)
  1379. this.y = other.y;
  1380. if (other.z < this.z)
  1381. this.z = other.z;
  1382. return this;
  1383. };
  1384. /**
  1385. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1386. * Returns the updated Vector3.
  1387. */
  1388. Vector3.prototype.MaximizeInPlace = function (other) {
  1389. if (other.x > this.x)
  1390. this.x = other.x;
  1391. if (other.y > this.y)
  1392. this.y = other.y;
  1393. if (other.z > this.z)
  1394. this.z = other.z;
  1395. return this;
  1396. };
  1397. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  1398. /**
  1399. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  1400. */
  1401. get: function () {
  1402. var absX = Math.abs(this.x);
  1403. var absY = Math.abs(this.y);
  1404. if (absX !== absY) {
  1405. return true;
  1406. }
  1407. var absZ = Math.abs(this.z);
  1408. if (absX !== absZ) {
  1409. return true;
  1410. }
  1411. if (absY !== absZ) {
  1412. return true;
  1413. }
  1414. return false;
  1415. },
  1416. enumerable: true,
  1417. configurable: true
  1418. });
  1419. // Properties
  1420. /**
  1421. * Returns the length of the Vector3 (float).
  1422. */
  1423. Vector3.prototype.length = function () {
  1424. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1425. };
  1426. /**
  1427. * Returns the squared length of the Vector3 (float).
  1428. */
  1429. Vector3.prototype.lengthSquared = function () {
  1430. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1431. };
  1432. // Methods
  1433. /**
  1434. * Normalize the current Vector3.
  1435. * Returns the updated Vector3.
  1436. */
  1437. Vector3.prototype.normalize = function () {
  1438. var len = this.length();
  1439. if (len === 0 || len === 1.0)
  1440. return this;
  1441. var num = 1.0 / len;
  1442. this.x *= num;
  1443. this.y *= num;
  1444. this.z *= num;
  1445. return this;
  1446. };
  1447. /**
  1448. * Returns a new Vector3 copied from the current Vector3.
  1449. */
  1450. Vector3.prototype.clone = function () {
  1451. return new Vector3(this.x, this.y, this.z);
  1452. };
  1453. /**
  1454. * Copies the passed vector coordinates to the current Vector3 ones.
  1455. * Returns the updated Vector3.
  1456. */
  1457. Vector3.prototype.copyFrom = function (source) {
  1458. this.x = source.x;
  1459. this.y = source.y;
  1460. this.z = source.z;
  1461. return this;
  1462. };
  1463. /**
  1464. * Copies the passed floats to the current Vector3 coordinates.
  1465. * Returns the updated Vector3.
  1466. */
  1467. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1468. this.x = x;
  1469. this.y = y;
  1470. this.z = z;
  1471. return this;
  1472. };
  1473. /**
  1474. * Copies the passed floats to the current Vector3 coordinates.
  1475. * Returns the updated Vector3.
  1476. */
  1477. Vector3.prototype.set = function (x, y, z) {
  1478. return this.copyFromFloats(x, y, z);
  1479. };
  1480. // Statics
  1481. /**
  1482. *
  1483. */
  1484. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1485. var d0 = Vector3.Dot(vector0, axis) - size;
  1486. var d1 = Vector3.Dot(vector1, axis) - size;
  1487. var s = d0 / (d0 - d1);
  1488. return s;
  1489. };
  1490. /**
  1491. * Returns a new Vector3 set from the index "offset" of the passed array.
  1492. */
  1493. Vector3.FromArray = function (array, offset) {
  1494. if (!offset) {
  1495. offset = 0;
  1496. }
  1497. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1498. };
  1499. /**
  1500. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1501. * This function is deprecated. Use FromArray instead.
  1502. */
  1503. Vector3.FromFloatArray = function (array, offset) {
  1504. return Vector3.FromArray(array, offset);
  1505. };
  1506. /**
  1507. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1508. */
  1509. Vector3.FromArrayToRef = function (array, offset, result) {
  1510. result.x = array[offset];
  1511. result.y = array[offset + 1];
  1512. result.z = array[offset + 2];
  1513. };
  1514. /**
  1515. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1516. * This function is deprecated. Use FromArrayToRef instead.
  1517. */
  1518. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1519. return Vector3.FromArrayToRef(array, offset, result);
  1520. };
  1521. /**
  1522. * Sets the passed vector "result" with the passed floats.
  1523. */
  1524. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1525. result.x = x;
  1526. result.y = y;
  1527. result.z = z;
  1528. };
  1529. /**
  1530. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1531. */
  1532. Vector3.Zero = function () {
  1533. return new Vector3(0.0, 0.0, 0.0);
  1534. };
  1535. /**
  1536. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1537. */
  1538. Vector3.One = function () {
  1539. return new Vector3(1.0, 1.0, 1.0);
  1540. };
  1541. /**
  1542. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1543. */
  1544. Vector3.Up = function () {
  1545. return new Vector3(0.0, 1.0, 0.0);
  1546. };
  1547. /**
  1548. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1549. */
  1550. Vector3.Forward = function () {
  1551. return new Vector3(0.0, 0.0, 1.0);
  1552. };
  1553. /**
  1554. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1555. */
  1556. Vector3.Right = function () {
  1557. return new Vector3(1.0, 0.0, 0.0);
  1558. };
  1559. /**
  1560. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1561. */
  1562. Vector3.Left = function () {
  1563. return new Vector3(-1.0, 0.0, 0.0);
  1564. };
  1565. /**
  1566. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1567. * This method computes tranformed coordinates only, not transformed direction vectors.
  1568. */
  1569. Vector3.TransformCoordinates = function (vector, transformation) {
  1570. var result = Vector3.Zero();
  1571. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1572. return result;
  1573. };
  1574. /**
  1575. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1576. * This method computes tranformed coordinates only, not transformed direction vectors.
  1577. */
  1578. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1579. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1580. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1581. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1582. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1583. result.x = x / w;
  1584. result.y = y / w;
  1585. result.z = z / w;
  1586. };
  1587. /**
  1588. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1589. * This method computes tranformed coordinates only, not transformed direction vectors.
  1590. */
  1591. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1592. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1593. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1594. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1595. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1596. result.x = rx / rw;
  1597. result.y = ry / rw;
  1598. result.z = rz / rw;
  1599. };
  1600. /**
  1601. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1602. * This methods computes transformed normalized direction vectors only.
  1603. */
  1604. Vector3.TransformNormal = function (vector, transformation) {
  1605. var result = Vector3.Zero();
  1606. Vector3.TransformNormalToRef(vector, transformation, result);
  1607. return result;
  1608. };
  1609. /**
  1610. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1611. * This methods computes transformed normalized direction vectors only.
  1612. */
  1613. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1614. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1615. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1616. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1617. result.x = x;
  1618. result.y = y;
  1619. result.z = z;
  1620. };
  1621. /**
  1622. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1623. * This methods computes transformed normalized direction vectors only.
  1624. */
  1625. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1626. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1627. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1628. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1629. };
  1630. /**
  1631. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1632. */
  1633. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1634. var squared = amount * amount;
  1635. var cubed = amount * squared;
  1636. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1637. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1638. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1639. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1640. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1641. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1642. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1643. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1644. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1645. return new Vector3(x, y, z);
  1646. };
  1647. /**
  1648. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max".
  1649. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1650. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1651. */
  1652. Vector3.Clamp = function (value, min, max) {
  1653. var x = value.x;
  1654. x = (x > max.x) ? max.x : x;
  1655. x = (x < min.x) ? min.x : x;
  1656. var y = value.y;
  1657. y = (y > max.y) ? max.y : y;
  1658. y = (y < min.y) ? min.y : y;
  1659. var z = value.z;
  1660. z = (z > max.z) ? max.z : z;
  1661. z = (z < min.z) ? min.z : z;
  1662. return new Vector3(x, y, z);
  1663. };
  1664. /**
  1665. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1666. */
  1667. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1668. var squared = amount * amount;
  1669. var cubed = amount * squared;
  1670. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1671. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1672. var part3 = (cubed - (2.0 * squared)) + amount;
  1673. var part4 = cubed - squared;
  1674. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1675. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1676. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1677. return new Vector3(x, y, z);
  1678. };
  1679. /**
  1680. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1681. */
  1682. Vector3.Lerp = function (start, end, amount) {
  1683. var result = new Vector3(0, 0, 0);
  1684. Vector3.LerpToRef(start, end, amount, result);
  1685. return result;
  1686. };
  1687. /**
  1688. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1689. */
  1690. Vector3.LerpToRef = function (start, end, amount, result) {
  1691. result.x = start.x + ((end.x - start.x) * amount);
  1692. result.y = start.y + ((end.y - start.y) * amount);
  1693. result.z = start.z + ((end.z - start.z) * amount);
  1694. };
  1695. /**
  1696. * Returns the dot product (float) between the vectors "left" and "right".
  1697. */
  1698. Vector3.Dot = function (left, right) {
  1699. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1700. };
  1701. /**
  1702. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1703. * The cross product is then orthogonal to both "left" and "right".
  1704. */
  1705. Vector3.Cross = function (left, right) {
  1706. var result = Vector3.Zero();
  1707. Vector3.CrossToRef(left, right, result);
  1708. return result;
  1709. };
  1710. /**
  1711. * Sets the passed vector "result" with the cross product of "left" and "right".
  1712. * The cross product is then orthogonal to both "left" and "right".
  1713. */
  1714. Vector3.CrossToRef = function (left, right, result) {
  1715. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1716. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1717. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1718. result.copyFrom(MathTmp.Vector3[0]);
  1719. };
  1720. /**
  1721. * Returns a new Vector3 as the normalization of the passed vector.
  1722. */
  1723. Vector3.Normalize = function (vector) {
  1724. var result = Vector3.Zero();
  1725. Vector3.NormalizeToRef(vector, result);
  1726. return result;
  1727. };
  1728. /**
  1729. * Sets the passed vector "result" with the normalization of the passed first vector.
  1730. */
  1731. Vector3.NormalizeToRef = function (vector, result) {
  1732. result.copyFrom(vector);
  1733. result.normalize();
  1734. };
  1735. Vector3.Project = function (vector, world, transform, viewport) {
  1736. var cw = viewport.width;
  1737. var ch = viewport.height;
  1738. var cx = viewport.x;
  1739. var cy = viewport.y;
  1740. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1741. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  1742. var matrix = MathTmp.Matrix[0];
  1743. world.multiplyToRef(transform, matrix);
  1744. matrix.multiplyToRef(viewportMatrix, matrix);
  1745. return Vector3.TransformCoordinates(vector, matrix);
  1746. };
  1747. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1748. var matrix = MathTmp.Matrix[0];
  1749. world.multiplyToRef(transform, matrix);
  1750. matrix.invert();
  1751. source.x = source.x / viewportWidth * 2 - 1;
  1752. source.y = -(source.y / viewportHeight * 2 - 1);
  1753. var vector = Vector3.TransformCoordinates(source, matrix);
  1754. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1755. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1756. vector = vector.scale(1.0 / num);
  1757. }
  1758. return vector;
  1759. };
  1760. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1761. var result = Vector3.Zero();
  1762. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  1763. return result;
  1764. };
  1765. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  1766. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  1767. };
  1768. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  1769. var matrix = MathTmp.Matrix[0];
  1770. world.multiplyToRef(view, matrix);
  1771. matrix.multiplyToRef(projection, matrix);
  1772. matrix.invert();
  1773. var screenSource = MathTmp.Vector3[0];
  1774. screenSource.x = sourceX / viewportWidth * 2 - 1;
  1775. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  1776. screenSource.z = 2 * sourceZ - 1.0;
  1777. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  1778. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1779. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1780. result.scaleInPlace(1.0 / num);
  1781. }
  1782. };
  1783. Vector3.Minimize = function (left, right) {
  1784. var min = left.clone();
  1785. min.MinimizeInPlace(right);
  1786. return min;
  1787. };
  1788. Vector3.Maximize = function (left, right) {
  1789. var max = left.clone();
  1790. max.MaximizeInPlace(right);
  1791. return max;
  1792. };
  1793. /**
  1794. * Returns the distance (float) between the vectors "value1" and "value2".
  1795. */
  1796. Vector3.Distance = function (value1, value2) {
  1797. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1798. };
  1799. /**
  1800. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1801. */
  1802. Vector3.DistanceSquared = function (value1, value2) {
  1803. var x = value1.x - value2.x;
  1804. var y = value1.y - value2.y;
  1805. var z = value1.z - value2.z;
  1806. return (x * x) + (y * y) + (z * z);
  1807. };
  1808. /**
  1809. * Returns a new Vector3 located at the center between "value1" and "value2".
  1810. */
  1811. Vector3.Center = function (value1, value2) {
  1812. var center = value1.add(value2);
  1813. center.scaleInPlace(0.5);
  1814. return center;
  1815. };
  1816. /**
  1817. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1818. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1819. * to something in order to rotate it from its local system to the given target system.
  1820. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1821. * Returns a new Vector3.
  1822. */
  1823. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1824. var rotation = Vector3.Zero();
  1825. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1826. return rotation;
  1827. };
  1828. /**
  1829. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1830. */
  1831. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1832. var quat = MathTmp.Quaternion[0];
  1833. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1834. quat.toEulerAnglesToRef(ref);
  1835. };
  1836. return Vector3;
  1837. }());
  1838. BABYLON.Vector3 = Vector3;
  1839. //Vector4 class created for EulerAngle class conversion to Quaternion
  1840. var Vector4 = /** @class */ (function () {
  1841. /**
  1842. * Creates a Vector4 object from the passed floats.
  1843. */
  1844. function Vector4(x, y, z, w) {
  1845. this.x = x;
  1846. this.y = y;
  1847. this.z = z;
  1848. this.w = w;
  1849. }
  1850. /**
  1851. * Returns the string with the Vector4 coordinates.
  1852. */
  1853. Vector4.prototype.toString = function () {
  1854. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1855. };
  1856. /**
  1857. * Returns the string "Vector4".
  1858. */
  1859. Vector4.prototype.getClassName = function () {
  1860. return "Vector4";
  1861. };
  1862. /**
  1863. * Returns the Vector4 hash code.
  1864. */
  1865. Vector4.prototype.getHashCode = function () {
  1866. var hash = this.x || 0;
  1867. hash = (hash * 397) ^ (this.y || 0);
  1868. hash = (hash * 397) ^ (this.z || 0);
  1869. hash = (hash * 397) ^ (this.w || 0);
  1870. return hash;
  1871. };
  1872. // Operators
  1873. /**
  1874. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1875. */
  1876. Vector4.prototype.asArray = function () {
  1877. var result = new Array();
  1878. this.toArray(result, 0);
  1879. return result;
  1880. };
  1881. /**
  1882. * Populates the passed array from the passed index with the Vector4 coordinates.
  1883. * Returns the Vector4.
  1884. */
  1885. Vector4.prototype.toArray = function (array, index) {
  1886. if (index === undefined) {
  1887. index = 0;
  1888. }
  1889. array[index] = this.x;
  1890. array[index + 1] = this.y;
  1891. array[index + 2] = this.z;
  1892. array[index + 3] = this.w;
  1893. return this;
  1894. };
  1895. /**
  1896. * Adds the passed vector to the current Vector4.
  1897. * Returns the updated Vector4.
  1898. */
  1899. Vector4.prototype.addInPlace = function (otherVector) {
  1900. this.x += otherVector.x;
  1901. this.y += otherVector.y;
  1902. this.z += otherVector.z;
  1903. this.w += otherVector.w;
  1904. return this;
  1905. };
  1906. /**
  1907. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1908. */
  1909. Vector4.prototype.add = function (otherVector) {
  1910. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1911. };
  1912. /**
  1913. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1914. * Returns the current Vector4.
  1915. */
  1916. Vector4.prototype.addToRef = function (otherVector, result) {
  1917. result.x = this.x + otherVector.x;
  1918. result.y = this.y + otherVector.y;
  1919. result.z = this.z + otherVector.z;
  1920. result.w = this.w + otherVector.w;
  1921. return this;
  1922. };
  1923. /**
  1924. * Subtract in place the passed vector from the current Vector4.
  1925. * Returns the updated Vector4.
  1926. */
  1927. Vector4.prototype.subtractInPlace = function (otherVector) {
  1928. this.x -= otherVector.x;
  1929. this.y -= otherVector.y;
  1930. this.z -= otherVector.z;
  1931. this.w -= otherVector.w;
  1932. return this;
  1933. };
  1934. /**
  1935. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1936. */
  1937. Vector4.prototype.subtract = function (otherVector) {
  1938. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1939. };
  1940. /**
  1941. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1942. * Returns the current Vector4.
  1943. */
  1944. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1945. result.x = this.x - otherVector.x;
  1946. result.y = this.y - otherVector.y;
  1947. result.z = this.z - otherVector.z;
  1948. result.w = this.w - otherVector.w;
  1949. return this;
  1950. };
  1951. /**
  1952. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1953. */
  1954. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1955. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1956. };
  1957. /**
  1958. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1959. * Returns the current Vector4.
  1960. */
  1961. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1962. result.x = this.x - x;
  1963. result.y = this.y - y;
  1964. result.z = this.z - z;
  1965. result.w = this.w - w;
  1966. return this;
  1967. };
  1968. /**
  1969. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1970. */
  1971. Vector4.prototype.negate = function () {
  1972. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1973. };
  1974. /**
  1975. * Multiplies the current Vector4 coordinates by scale (float).
  1976. * Returns the updated Vector4.
  1977. */
  1978. Vector4.prototype.scaleInPlace = function (scale) {
  1979. this.x *= scale;
  1980. this.y *= scale;
  1981. this.z *= scale;
  1982. this.w *= scale;
  1983. return this;
  1984. };
  1985. /**
  1986. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1987. */
  1988. Vector4.prototype.scale = function (scale) {
  1989. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1990. };
  1991. /**
  1992. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1993. * Returns the current Vector4.
  1994. */
  1995. Vector4.prototype.scaleToRef = function (scale, result) {
  1996. result.x = this.x * scale;
  1997. result.y = this.y * scale;
  1998. result.z = this.z * scale;
  1999. result.w = this.w * scale;
  2000. return this;
  2001. };
  2002. /**
  2003. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  2004. */
  2005. Vector4.prototype.equals = function (otherVector) {
  2006. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  2007. };
  2008. /**
  2009. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  2010. */
  2011. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2012. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2013. return otherVector
  2014. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2015. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2016. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2017. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2018. };
  2019. /**
  2020. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  2021. */
  2022. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  2023. return this.x === x && this.y === y && this.z === z && this.w === w;
  2024. };
  2025. /**
  2026. * Multiplies in place the current Vector4 by the passed one.
  2027. * Returns the updated Vector4.
  2028. */
  2029. Vector4.prototype.multiplyInPlace = function (otherVector) {
  2030. this.x *= otherVector.x;
  2031. this.y *= otherVector.y;
  2032. this.z *= otherVector.z;
  2033. this.w *= otherVector.w;
  2034. return this;
  2035. };
  2036. /**
  2037. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2038. */
  2039. Vector4.prototype.multiply = function (otherVector) {
  2040. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2041. };
  2042. /**
  2043. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2044. * Returns the current Vector4.
  2045. */
  2046. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2047. result.x = this.x * otherVector.x;
  2048. result.y = this.y * otherVector.y;
  2049. result.z = this.z * otherVector.z;
  2050. result.w = this.w * otherVector.w;
  2051. return this;
  2052. };
  2053. /**
  2054. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2055. */
  2056. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2057. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2058. };
  2059. /**
  2060. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2061. */
  2062. Vector4.prototype.divide = function (otherVector) {
  2063. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2064. };
  2065. /**
  2066. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2067. * Returns the current Vector4.
  2068. */
  2069. Vector4.prototype.divideToRef = function (otherVector, result) {
  2070. result.x = this.x / otherVector.x;
  2071. result.y = this.y / otherVector.y;
  2072. result.z = this.z / otherVector.z;
  2073. result.w = this.w / otherVector.w;
  2074. return this;
  2075. };
  2076. /**
  2077. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2078. */
  2079. Vector4.prototype.MinimizeInPlace = function (other) {
  2080. if (other.x < this.x)
  2081. this.x = other.x;
  2082. if (other.y < this.y)
  2083. this.y = other.y;
  2084. if (other.z < this.z)
  2085. this.z = other.z;
  2086. if (other.w < this.w)
  2087. this.w = other.w;
  2088. return this;
  2089. };
  2090. /**
  2091. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2092. */
  2093. Vector4.prototype.MaximizeInPlace = function (other) {
  2094. if (other.x > this.x)
  2095. this.x = other.x;
  2096. if (other.y > this.y)
  2097. this.y = other.y;
  2098. if (other.z > this.z)
  2099. this.z = other.z;
  2100. if (other.w > this.w)
  2101. this.w = other.w;
  2102. return this;
  2103. };
  2104. // Properties
  2105. /**
  2106. * Returns the Vector4 length (float).
  2107. */
  2108. Vector4.prototype.length = function () {
  2109. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2110. };
  2111. /**
  2112. * Returns the Vector4 squared length (float).
  2113. */
  2114. Vector4.prototype.lengthSquared = function () {
  2115. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2116. };
  2117. // Methods
  2118. /**
  2119. * Normalizes in place the Vector4.
  2120. * Returns the updated Vector4.
  2121. */
  2122. Vector4.prototype.normalize = function () {
  2123. var len = this.length();
  2124. if (len === 0)
  2125. return this;
  2126. var num = 1.0 / len;
  2127. this.x *= num;
  2128. this.y *= num;
  2129. this.z *= num;
  2130. this.w *= num;
  2131. return this;
  2132. };
  2133. /**
  2134. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  2135. */
  2136. Vector4.prototype.toVector3 = function () {
  2137. return new Vector3(this.x, this.y, this.z);
  2138. };
  2139. /**
  2140. * Returns a new Vector4 copied from the current one.
  2141. */
  2142. Vector4.prototype.clone = function () {
  2143. return new Vector4(this.x, this.y, this.z, this.w);
  2144. };
  2145. /**
  2146. * Updates the current Vector4 with the passed one coordinates.
  2147. * Returns the updated Vector4.
  2148. */
  2149. Vector4.prototype.copyFrom = function (source) {
  2150. this.x = source.x;
  2151. this.y = source.y;
  2152. this.z = source.z;
  2153. this.w = source.w;
  2154. return this;
  2155. };
  2156. /**
  2157. * Updates the current Vector4 coordinates with the passed floats.
  2158. * Returns the updated Vector4.
  2159. */
  2160. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  2161. this.x = x;
  2162. this.y = y;
  2163. this.z = z;
  2164. this.w = w;
  2165. return this;
  2166. };
  2167. /**
  2168. * Updates the current Vector4 coordinates with the passed floats.
  2169. * Returns the updated Vector4.
  2170. */
  2171. Vector4.prototype.set = function (x, y, z, w) {
  2172. return this.copyFromFloats(x, y, z, w);
  2173. };
  2174. // Statics
  2175. /**
  2176. * Returns a new Vector4 set from the starting index of the passed array.
  2177. */
  2178. Vector4.FromArray = function (array, offset) {
  2179. if (!offset) {
  2180. offset = 0;
  2181. }
  2182. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2183. };
  2184. /**
  2185. * Updates the passed vector "result" from the starting index of the passed array.
  2186. */
  2187. Vector4.FromArrayToRef = function (array, offset, result) {
  2188. result.x = array[offset];
  2189. result.y = array[offset + 1];
  2190. result.z = array[offset + 2];
  2191. result.w = array[offset + 3];
  2192. };
  2193. /**
  2194. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2195. */
  2196. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2197. Vector4.FromArrayToRef(array, offset, result);
  2198. };
  2199. /**
  2200. * Updates the passed vector "result" coordinates from the passed floats.
  2201. */
  2202. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2203. result.x = x;
  2204. result.y = y;
  2205. result.z = z;
  2206. result.w = w;
  2207. };
  2208. /**
  2209. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2210. */
  2211. Vector4.Zero = function () {
  2212. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2213. };
  2214. /**
  2215. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2216. */
  2217. Vector4.One = function () {
  2218. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2219. };
  2220. /**
  2221. * Returns a new normalized Vector4 from the passed one.
  2222. */
  2223. Vector4.Normalize = function (vector) {
  2224. var result = Vector4.Zero();
  2225. Vector4.NormalizeToRef(vector, result);
  2226. return result;
  2227. };
  2228. /**
  2229. * Updates the passed vector "result" from the normalization of the passed one.
  2230. */
  2231. Vector4.NormalizeToRef = function (vector, result) {
  2232. result.copyFrom(vector);
  2233. result.normalize();
  2234. };
  2235. Vector4.Minimize = function (left, right) {
  2236. var min = left.clone();
  2237. min.MinimizeInPlace(right);
  2238. return min;
  2239. };
  2240. Vector4.Maximize = function (left, right) {
  2241. var max = left.clone();
  2242. max.MaximizeInPlace(right);
  2243. return max;
  2244. };
  2245. /**
  2246. * Returns the distance (float) between the vectors "value1" and "value2".
  2247. */
  2248. Vector4.Distance = function (value1, value2) {
  2249. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2250. };
  2251. /**
  2252. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2253. */
  2254. Vector4.DistanceSquared = function (value1, value2) {
  2255. var x = value1.x - value2.x;
  2256. var y = value1.y - value2.y;
  2257. var z = value1.z - value2.z;
  2258. var w = value1.w - value2.w;
  2259. return (x * x) + (y * y) + (z * z) + (w * w);
  2260. };
  2261. /**
  2262. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2263. */
  2264. Vector4.Center = function (value1, value2) {
  2265. var center = value1.add(value2);
  2266. center.scaleInPlace(0.5);
  2267. return center;
  2268. };
  2269. /**
  2270. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2271. * This methods computes transformed normalized direction vectors only.
  2272. */
  2273. Vector4.TransformNormal = function (vector, transformation) {
  2274. var result = Vector4.Zero();
  2275. Vector4.TransformNormalToRef(vector, transformation, result);
  2276. return result;
  2277. };
  2278. /**
  2279. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2280. * This methods computes transformed normalized direction vectors only.
  2281. */
  2282. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2283. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2284. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2285. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2286. result.x = x;
  2287. result.y = y;
  2288. result.z = z;
  2289. result.w = vector.w;
  2290. };
  2291. /**
  2292. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2293. * This methods computes transformed normalized direction vectors only.
  2294. */
  2295. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2296. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2297. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2298. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2299. result.w = w;
  2300. };
  2301. return Vector4;
  2302. }());
  2303. BABYLON.Vector4 = Vector4;
  2304. var Size = /** @class */ (function () {
  2305. /**
  2306. * Creates a Size object from the passed width and height (floats).
  2307. */
  2308. function Size(width, height) {
  2309. this.width = width;
  2310. this.height = height;
  2311. }
  2312. // Returns a string with the Size width and height.
  2313. Size.prototype.toString = function () {
  2314. return "{W: " + this.width + ", H: " + this.height + "}";
  2315. };
  2316. /**
  2317. * Returns the string "Size"
  2318. */
  2319. Size.prototype.getClassName = function () {
  2320. return "Size";
  2321. };
  2322. /**
  2323. * Returns the Size hash code.
  2324. */
  2325. Size.prototype.getHashCode = function () {
  2326. var hash = this.width || 0;
  2327. hash = (hash * 397) ^ (this.height || 0);
  2328. return hash;
  2329. };
  2330. /**
  2331. * Updates the current size from the passed one.
  2332. * Returns the updated Size.
  2333. */
  2334. Size.prototype.copyFrom = function (src) {
  2335. this.width = src.width;
  2336. this.height = src.height;
  2337. };
  2338. /**
  2339. * Updates in place the current Size from the passed floats.
  2340. * Returns the updated Size.
  2341. */
  2342. Size.prototype.copyFromFloats = function (width, height) {
  2343. this.width = width;
  2344. this.height = height;
  2345. return this;
  2346. };
  2347. /**
  2348. * Updates in place the current Size from the passed floats.
  2349. * Returns the updated Size.
  2350. */
  2351. Size.prototype.set = function (width, height) {
  2352. return this.copyFromFloats(width, height);
  2353. };
  2354. /**
  2355. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2356. */
  2357. Size.prototype.multiplyByFloats = function (w, h) {
  2358. return new Size(this.width * w, this.height * h);
  2359. };
  2360. /**
  2361. * Returns a new Size copied from the passed one.
  2362. */
  2363. Size.prototype.clone = function () {
  2364. return new Size(this.width, this.height);
  2365. };
  2366. /**
  2367. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2368. */
  2369. Size.prototype.equals = function (other) {
  2370. if (!other) {
  2371. return false;
  2372. }
  2373. return (this.width === other.width) && (this.height === other.height);
  2374. };
  2375. Object.defineProperty(Size.prototype, "surface", {
  2376. /**
  2377. * Returns the surface of the Size : width * height (float).
  2378. */
  2379. get: function () {
  2380. return this.width * this.height;
  2381. },
  2382. enumerable: true,
  2383. configurable: true
  2384. });
  2385. /**
  2386. * Returns a new Size set to (0.0, 0.0)
  2387. */
  2388. Size.Zero = function () {
  2389. return new Size(0.0, 0.0);
  2390. };
  2391. /**
  2392. * Returns a new Size set as the addition result of the current Size and the passed one.
  2393. */
  2394. Size.prototype.add = function (otherSize) {
  2395. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2396. return r;
  2397. };
  2398. /**
  2399. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2400. */
  2401. Size.prototype.subtract = function (otherSize) {
  2402. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2403. return r;
  2404. };
  2405. /**
  2406. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2407. */
  2408. Size.Lerp = function (start, end, amount) {
  2409. var w = start.width + ((end.width - start.width) * amount);
  2410. var h = start.height + ((end.height - start.height) * amount);
  2411. return new Size(w, h);
  2412. };
  2413. return Size;
  2414. }());
  2415. BABYLON.Size = Size;
  2416. var Quaternion = /** @class */ (function () {
  2417. /**
  2418. * Creates a new Quaternion from the passed floats.
  2419. */
  2420. function Quaternion(x, y, z, w) {
  2421. if (x === void 0) { x = 0.0; }
  2422. if (y === void 0) { y = 0.0; }
  2423. if (z === void 0) { z = 0.0; }
  2424. if (w === void 0) { w = 1.0; }
  2425. this.x = x;
  2426. this.y = y;
  2427. this.z = z;
  2428. this.w = w;
  2429. }
  2430. /**
  2431. * Returns a string with the Quaternion coordinates.
  2432. */
  2433. Quaternion.prototype.toString = function () {
  2434. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2435. };
  2436. /**
  2437. * Returns the string "Quaternion".
  2438. */
  2439. Quaternion.prototype.getClassName = function () {
  2440. return "Quaternion";
  2441. };
  2442. /**
  2443. * Returns the Quaternion hash code.
  2444. */
  2445. Quaternion.prototype.getHashCode = function () {
  2446. var hash = this.x || 0;
  2447. hash = (hash * 397) ^ (this.y || 0);
  2448. hash = (hash * 397) ^ (this.z || 0);
  2449. hash = (hash * 397) ^ (this.w || 0);
  2450. return hash;
  2451. };
  2452. /**
  2453. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2454. */
  2455. Quaternion.prototype.asArray = function () {
  2456. return [this.x, this.y, this.z, this.w];
  2457. };
  2458. /**
  2459. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2460. */
  2461. Quaternion.prototype.equals = function (otherQuaternion) {
  2462. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2463. };
  2464. /**
  2465. * Returns a new Quaternion copied from the current one.
  2466. */
  2467. Quaternion.prototype.clone = function () {
  2468. return new Quaternion(this.x, this.y, this.z, this.w);
  2469. };
  2470. /**
  2471. * Updates the current Quaternion from the passed one coordinates.
  2472. * Returns the updated Quaterion.
  2473. */
  2474. Quaternion.prototype.copyFrom = function (other) {
  2475. this.x = other.x;
  2476. this.y = other.y;
  2477. this.z = other.z;
  2478. this.w = other.w;
  2479. return this;
  2480. };
  2481. /**
  2482. * Updates the current Quaternion from the passed float coordinates.
  2483. * Returns the updated Quaterion.
  2484. */
  2485. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2486. this.x = x;
  2487. this.y = y;
  2488. this.z = z;
  2489. this.w = w;
  2490. return this;
  2491. };
  2492. /**
  2493. * Updates the current Quaternion from the passed float coordinates.
  2494. * Returns the updated Quaterion.
  2495. */
  2496. Quaternion.prototype.set = function (x, y, z, w) {
  2497. return this.copyFromFloats(x, y, z, w);
  2498. };
  2499. /**
  2500. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2501. */
  2502. Quaternion.prototype.add = function (other) {
  2503. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2504. };
  2505. /**
  2506. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2507. */
  2508. Quaternion.prototype.subtract = function (other) {
  2509. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2510. };
  2511. /**
  2512. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2513. */
  2514. Quaternion.prototype.scale = function (value) {
  2515. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2516. };
  2517. /**
  2518. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2519. */
  2520. Quaternion.prototype.multiply = function (q1) {
  2521. var result = new Quaternion(0, 0, 0, 1.0);
  2522. this.multiplyToRef(q1, result);
  2523. return result;
  2524. };
  2525. /**
  2526. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2527. * Returns the current Quaternion.
  2528. */
  2529. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2530. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2531. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2532. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2533. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2534. result.copyFromFloats(x, y, z, w);
  2535. return this;
  2536. };
  2537. /**
  2538. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2539. * Returns the updated Quaternion.
  2540. */
  2541. Quaternion.prototype.multiplyInPlace = function (q1) {
  2542. this.multiplyToRef(q1, this);
  2543. return this;
  2544. };
  2545. /**
  2546. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2547. * Returns the current Quaternion.
  2548. */
  2549. Quaternion.prototype.conjugateToRef = function (ref) {
  2550. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2551. return this;
  2552. };
  2553. /**
  2554. * Conjugates in place the current Quaternion.
  2555. * Returns the updated Quaternion.
  2556. */
  2557. Quaternion.prototype.conjugateInPlace = function () {
  2558. this.x *= -1;
  2559. this.y *= -1;
  2560. this.z *= -1;
  2561. return this;
  2562. };
  2563. /**
  2564. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2565. */
  2566. Quaternion.prototype.conjugate = function () {
  2567. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2568. return result;
  2569. };
  2570. /**
  2571. * Returns the Quaternion length (float).
  2572. */
  2573. Quaternion.prototype.length = function () {
  2574. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2575. };
  2576. /**
  2577. * Normalize in place the current Quaternion.
  2578. * Returns the updated Quaternion.
  2579. */
  2580. Quaternion.prototype.normalize = function () {
  2581. var length = 1.0 / this.length();
  2582. this.x *= length;
  2583. this.y *= length;
  2584. this.z *= length;
  2585. this.w *= length;
  2586. return this;
  2587. };
  2588. /**
  2589. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2590. */
  2591. Quaternion.prototype.toEulerAngles = function (order) {
  2592. if (order === void 0) { order = "YZX"; }
  2593. var result = Vector3.Zero();
  2594. this.toEulerAnglesToRef(result, order);
  2595. return result;
  2596. };
  2597. /**
  2598. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2599. * Returns the current Quaternion.
  2600. */
  2601. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2602. if (order === void 0) { order = "YZX"; }
  2603. var qz = this.z;
  2604. var qx = this.x;
  2605. var qy = this.y;
  2606. var qw = this.w;
  2607. var sqw = qw * qw;
  2608. var sqz = qz * qz;
  2609. var sqx = qx * qx;
  2610. var sqy = qy * qy;
  2611. var zAxisY = qy * qz - qx * qw;
  2612. var limit = .4999999;
  2613. if (zAxisY < -limit) {
  2614. result.y = 2 * Math.atan2(qy, qw);
  2615. result.x = Math.PI / 2;
  2616. result.z = 0;
  2617. }
  2618. else if (zAxisY > limit) {
  2619. result.y = 2 * Math.atan2(qy, qw);
  2620. result.x = -Math.PI / 2;
  2621. result.z = 0;
  2622. }
  2623. else {
  2624. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2625. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2626. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2627. }
  2628. return this;
  2629. };
  2630. /**
  2631. * Updates the passed rotation matrix with the current Quaternion values.
  2632. * Returns the current Quaternion.
  2633. */
  2634. Quaternion.prototype.toRotationMatrix = function (result) {
  2635. var xx = this.x * this.x;
  2636. var yy = this.y * this.y;
  2637. var zz = this.z * this.z;
  2638. var xy = this.x * this.y;
  2639. var zw = this.z * this.w;
  2640. var zx = this.z * this.x;
  2641. var yw = this.y * this.w;
  2642. var yz = this.y * this.z;
  2643. var xw = this.x * this.w;
  2644. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2645. result.m[1] = 2.0 * (xy + zw);
  2646. result.m[2] = 2.0 * (zx - yw);
  2647. result.m[3] = 0;
  2648. result.m[4] = 2.0 * (xy - zw);
  2649. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2650. result.m[6] = 2.0 * (yz + xw);
  2651. result.m[7] = 0;
  2652. result.m[8] = 2.0 * (zx + yw);
  2653. result.m[9] = 2.0 * (yz - xw);
  2654. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2655. result.m[11] = 0;
  2656. result.m[12] = 0;
  2657. result.m[13] = 0;
  2658. result.m[14] = 0;
  2659. result.m[15] = 1.0;
  2660. result._markAsUpdated();
  2661. return this;
  2662. };
  2663. /**
  2664. * Updates the current Quaternion from the passed rotation matrix values.
  2665. * Returns the updated Quaternion.
  2666. */
  2667. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2668. Quaternion.FromRotationMatrixToRef(matrix, this);
  2669. return this;
  2670. };
  2671. // Statics
  2672. /**
  2673. * Returns a new Quaternion set from the passed rotation matrix values.
  2674. */
  2675. Quaternion.FromRotationMatrix = function (matrix) {
  2676. var result = new Quaternion();
  2677. Quaternion.FromRotationMatrixToRef(matrix, result);
  2678. return result;
  2679. };
  2680. /**
  2681. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2682. */
  2683. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2684. var data = matrix.m;
  2685. var m11 = data[0], m12 = data[4], m13 = data[8];
  2686. var m21 = data[1], m22 = data[5], m23 = data[9];
  2687. var m31 = data[2], m32 = data[6], m33 = data[10];
  2688. var trace = m11 + m22 + m33;
  2689. var s;
  2690. if (trace > 0) {
  2691. s = 0.5 / Math.sqrt(trace + 1.0);
  2692. result.w = 0.25 / s;
  2693. result.x = (m32 - m23) * s;
  2694. result.y = (m13 - m31) * s;
  2695. result.z = (m21 - m12) * s;
  2696. }
  2697. else if (m11 > m22 && m11 > m33) {
  2698. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2699. result.w = (m32 - m23) / s;
  2700. result.x = 0.25 * s;
  2701. result.y = (m12 + m21) / s;
  2702. result.z = (m13 + m31) / s;
  2703. }
  2704. else if (m22 > m33) {
  2705. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2706. result.w = (m13 - m31) / s;
  2707. result.x = (m12 + m21) / s;
  2708. result.y = 0.25 * s;
  2709. result.z = (m23 + m32) / s;
  2710. }
  2711. else {
  2712. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2713. result.w = (m21 - m12) / s;
  2714. result.x = (m13 + m31) / s;
  2715. result.y = (m23 + m32) / s;
  2716. result.z = 0.25 * s;
  2717. }
  2718. };
  2719. /**
  2720. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2721. */
  2722. Quaternion.Zero = function () {
  2723. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2724. };
  2725. /**
  2726. * Returns a new Quaternion as the inverted current Quaternion.
  2727. */
  2728. Quaternion.Inverse = function (q) {
  2729. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2730. };
  2731. /**
  2732. * Returns the identity Quaternion.
  2733. */
  2734. Quaternion.Identity = function () {
  2735. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2736. };
  2737. Quaternion.IsIdentity = function (quaternion) {
  2738. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2739. };
  2740. /**
  2741. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2742. */
  2743. Quaternion.RotationAxis = function (axis, angle) {
  2744. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2745. };
  2746. /**
  2747. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2748. */
  2749. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2750. var sin = Math.sin(angle / 2);
  2751. axis.normalize();
  2752. result.w = Math.cos(angle / 2);
  2753. result.x = axis.x * sin;
  2754. result.y = axis.y * sin;
  2755. result.z = axis.z * sin;
  2756. return result;
  2757. };
  2758. /**
  2759. * Retuns a new Quaternion set from the starting index of the passed array.
  2760. */
  2761. Quaternion.FromArray = function (array, offset) {
  2762. if (!offset) {
  2763. offset = 0;
  2764. }
  2765. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2766. };
  2767. /**
  2768. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2769. */
  2770. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2771. var q = new Quaternion();
  2772. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2773. return q;
  2774. };
  2775. /**
  2776. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2777. */
  2778. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2779. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2780. var halfRoll = roll * 0.5;
  2781. var halfPitch = pitch * 0.5;
  2782. var halfYaw = yaw * 0.5;
  2783. var sinRoll = Math.sin(halfRoll);
  2784. var cosRoll = Math.cos(halfRoll);
  2785. var sinPitch = Math.sin(halfPitch);
  2786. var cosPitch = Math.cos(halfPitch);
  2787. var sinYaw = Math.sin(halfYaw);
  2788. var cosYaw = Math.cos(halfYaw);
  2789. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2790. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2791. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2792. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2793. };
  2794. /**
  2795. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2796. */
  2797. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2798. var result = new Quaternion();
  2799. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2800. return result;
  2801. };
  2802. /**
  2803. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2804. */
  2805. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2806. // Produces a quaternion from Euler angles in the z-x-z orientation
  2807. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2808. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2809. var halfBeta = beta * 0.5;
  2810. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2811. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2812. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2813. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2814. };
  2815. /**
  2816. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2817. * cf to Vector3.RotationFromAxis() documentation.
  2818. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2819. */
  2820. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2821. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2822. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2823. return quat;
  2824. };
  2825. /**
  2826. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2827. * cf to Vector3.RotationFromAxis() documentation.
  2828. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2829. */
  2830. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2831. var rotMat = MathTmp.Matrix[0];
  2832. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2833. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2834. };
  2835. Quaternion.Slerp = function (left, right, amount) {
  2836. var result = Quaternion.Identity();
  2837. Quaternion.SlerpToRef(left, right, amount, result);
  2838. return result;
  2839. };
  2840. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2841. var num2;
  2842. var num3;
  2843. var num = amount;
  2844. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2845. var flag = false;
  2846. if (num4 < 0) {
  2847. flag = true;
  2848. num4 = -num4;
  2849. }
  2850. if (num4 > 0.999999) {
  2851. num3 = 1 - num;
  2852. num2 = flag ? -num : num;
  2853. }
  2854. else {
  2855. var num5 = Math.acos(num4);
  2856. var num6 = (1.0 / Math.sin(num5));
  2857. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2858. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2859. }
  2860. result.x = (num3 * left.x) + (num2 * right.x);
  2861. result.y = (num3 * left.y) + (num2 * right.y);
  2862. result.z = (num3 * left.z) + (num2 * right.z);
  2863. result.w = (num3 * left.w) + (num2 * right.w);
  2864. };
  2865. /**
  2866. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2867. */
  2868. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2869. var squared = amount * amount;
  2870. var cubed = amount * squared;
  2871. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2872. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2873. var part3 = (cubed - (2.0 * squared)) + amount;
  2874. var part4 = cubed - squared;
  2875. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2876. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2877. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2878. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2879. return new Quaternion(x, y, z, w);
  2880. };
  2881. return Quaternion;
  2882. }());
  2883. BABYLON.Quaternion = Quaternion;
  2884. var Matrix = /** @class */ (function () {
  2885. function Matrix() {
  2886. this._isIdentity = false;
  2887. this._isIdentityDirty = true;
  2888. this.m = new Float32Array(16);
  2889. this._markAsUpdated();
  2890. }
  2891. Matrix.prototype._markAsUpdated = function () {
  2892. this.updateFlag = Matrix._updateFlagSeed++;
  2893. this._isIdentityDirty = true;
  2894. };
  2895. // Properties
  2896. /**
  2897. * Boolean : True is the matrix is the identity matrix
  2898. */
  2899. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2900. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2901. if (this._isIdentityDirty) {
  2902. this._isIdentityDirty = false;
  2903. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2904. this._isIdentity = false;
  2905. }
  2906. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2907. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2908. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2909. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2910. this._isIdentity = false;
  2911. }
  2912. else {
  2913. this._isIdentity = true;
  2914. }
  2915. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2916. this._isIdentity = false;
  2917. }
  2918. }
  2919. return this._isIdentity;
  2920. };
  2921. /**
  2922. * Returns the matrix determinant (float).
  2923. */
  2924. Matrix.prototype.determinant = function () {
  2925. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2926. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2927. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2928. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2929. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2930. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2931. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2932. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2933. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2934. };
  2935. // Methods
  2936. /**
  2937. * Returns the matrix underlying array.
  2938. */
  2939. Matrix.prototype.toArray = function () {
  2940. return this.m;
  2941. };
  2942. /**
  2943. * Returns the matrix underlying array.
  2944. */
  2945. Matrix.prototype.asArray = function () {
  2946. return this.toArray();
  2947. };
  2948. /**
  2949. * Inverts in place the Matrix.
  2950. * Returns the Matrix inverted.
  2951. */
  2952. Matrix.prototype.invert = function () {
  2953. this.invertToRef(this);
  2954. return this;
  2955. };
  2956. /**
  2957. * Sets all the matrix elements to zero.
  2958. * Returns the Matrix.
  2959. */
  2960. Matrix.prototype.reset = function () {
  2961. for (var index = 0; index < 16; index++) {
  2962. this.m[index] = 0.0;
  2963. }
  2964. this._markAsUpdated();
  2965. return this;
  2966. };
  2967. /**
  2968. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2969. */
  2970. Matrix.prototype.add = function (other) {
  2971. var result = new Matrix();
  2972. this.addToRef(other, result);
  2973. return result;
  2974. };
  2975. /**
  2976. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2977. * Returns the Matrix.
  2978. */
  2979. Matrix.prototype.addToRef = function (other, result) {
  2980. for (var index = 0; index < 16; index++) {
  2981. result.m[index] = this.m[index] + other.m[index];
  2982. }
  2983. result._markAsUpdated();
  2984. return this;
  2985. };
  2986. /**
  2987. * Adds in place the passed matrix to the current Matrix.
  2988. * Returns the updated Matrix.
  2989. */
  2990. Matrix.prototype.addToSelf = function (other) {
  2991. for (var index = 0; index < 16; index++) {
  2992. this.m[index] += other.m[index];
  2993. }
  2994. this._markAsUpdated();
  2995. return this;
  2996. };
  2997. /**
  2998. * Sets the passed matrix with the current inverted Matrix.
  2999. * Returns the unmodified current Matrix.
  3000. */
  3001. Matrix.prototype.invertToRef = function (other) {
  3002. var l1 = this.m[0];
  3003. var l2 = this.m[1];
  3004. var l3 = this.m[2];
  3005. var l4 = this.m[3];
  3006. var l5 = this.m[4];
  3007. var l6 = this.m[5];
  3008. var l7 = this.m[6];
  3009. var l8 = this.m[7];
  3010. var l9 = this.m[8];
  3011. var l10 = this.m[9];
  3012. var l11 = this.m[10];
  3013. var l12 = this.m[11];
  3014. var l13 = this.m[12];
  3015. var l14 = this.m[13];
  3016. var l15 = this.m[14];
  3017. var l16 = this.m[15];
  3018. var l17 = (l11 * l16) - (l12 * l15);
  3019. var l18 = (l10 * l16) - (l12 * l14);
  3020. var l19 = (l10 * l15) - (l11 * l14);
  3021. var l20 = (l9 * l16) - (l12 * l13);
  3022. var l21 = (l9 * l15) - (l11 * l13);
  3023. var l22 = (l9 * l14) - (l10 * l13);
  3024. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  3025. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  3026. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  3027. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  3028. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  3029. var l28 = (l7 * l16) - (l8 * l15);
  3030. var l29 = (l6 * l16) - (l8 * l14);
  3031. var l30 = (l6 * l15) - (l7 * l14);
  3032. var l31 = (l5 * l16) - (l8 * l13);
  3033. var l32 = (l5 * l15) - (l7 * l13);
  3034. var l33 = (l5 * l14) - (l6 * l13);
  3035. var l34 = (l7 * l12) - (l8 * l11);
  3036. var l35 = (l6 * l12) - (l8 * l10);
  3037. var l36 = (l6 * l11) - (l7 * l10);
  3038. var l37 = (l5 * l12) - (l8 * l9);
  3039. var l38 = (l5 * l11) - (l7 * l9);
  3040. var l39 = (l5 * l10) - (l6 * l9);
  3041. other.m[0] = l23 * l27;
  3042. other.m[4] = l24 * l27;
  3043. other.m[8] = l25 * l27;
  3044. other.m[12] = l26 * l27;
  3045. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3046. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3047. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3048. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3049. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3050. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3051. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3052. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3053. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3054. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3055. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3056. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3057. other._markAsUpdated();
  3058. return this;
  3059. };
  3060. /**
  3061. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3062. * Returns the updated Matrix.
  3063. */
  3064. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3065. this.m[12] = x;
  3066. this.m[13] = y;
  3067. this.m[14] = z;
  3068. this._markAsUpdated();
  3069. return this;
  3070. };
  3071. /**
  3072. * Inserts the translation vector in the current Matrix.
  3073. * Returns the updated Matrix.
  3074. */
  3075. Matrix.prototype.setTranslation = function (vector3) {
  3076. this.m[12] = vector3.x;
  3077. this.m[13] = vector3.y;
  3078. this.m[14] = vector3.z;
  3079. this._markAsUpdated();
  3080. return this;
  3081. };
  3082. /**
  3083. * Returns a new Vector3 as the extracted translation from the Matrix.
  3084. */
  3085. Matrix.prototype.getTranslation = function () {
  3086. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3087. };
  3088. /**
  3089. * Fill a Vector3 with the extracted translation from the Matrix.
  3090. */
  3091. Matrix.prototype.getTranslationToRef = function (result) {
  3092. result.x = this.m[12];
  3093. result.y = this.m[13];
  3094. result.z = this.m[14];
  3095. return this;
  3096. };
  3097. /**
  3098. * Remove rotation and scaling part from the Matrix.
  3099. * Returns the updated Matrix.
  3100. */
  3101. Matrix.prototype.removeRotationAndScaling = function () {
  3102. this.setRowFromFloats(0, 1, 0, 0, 0);
  3103. this.setRowFromFloats(1, 0, 1, 0, 0);
  3104. this.setRowFromFloats(2, 0, 0, 1, 0);
  3105. return this;
  3106. };
  3107. /**
  3108. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3109. */
  3110. Matrix.prototype.multiply = function (other) {
  3111. var result = new Matrix();
  3112. this.multiplyToRef(other, result);
  3113. return result;
  3114. };
  3115. /**
  3116. * Updates the current Matrix from the passed one values.
  3117. * Returns the updated Matrix.
  3118. */
  3119. Matrix.prototype.copyFrom = function (other) {
  3120. for (var index = 0; index < 16; index++) {
  3121. this.m[index] = other.m[index];
  3122. }
  3123. this._markAsUpdated();
  3124. return this;
  3125. };
  3126. /**
  3127. * Populates the passed array from the starting index with the Matrix values.
  3128. * Returns the Matrix.
  3129. */
  3130. Matrix.prototype.copyToArray = function (array, offset) {
  3131. if (offset === void 0) { offset = 0; }
  3132. for (var index = 0; index < 16; index++) {
  3133. array[offset + index] = this.m[index];
  3134. }
  3135. return this;
  3136. };
  3137. /**
  3138. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  3139. */
  3140. Matrix.prototype.multiplyToRef = function (other, result) {
  3141. this.multiplyToArray(other, result.m, 0);
  3142. result._markAsUpdated();
  3143. return this;
  3144. };
  3145. /**
  3146. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  3147. */
  3148. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  3149. var tm0 = this.m[0];
  3150. var tm1 = this.m[1];
  3151. var tm2 = this.m[2];
  3152. var tm3 = this.m[3];
  3153. var tm4 = this.m[4];
  3154. var tm5 = this.m[5];
  3155. var tm6 = this.m[6];
  3156. var tm7 = this.m[7];
  3157. var tm8 = this.m[8];
  3158. var tm9 = this.m[9];
  3159. var tm10 = this.m[10];
  3160. var tm11 = this.m[11];
  3161. var tm12 = this.m[12];
  3162. var tm13 = this.m[13];
  3163. var tm14 = this.m[14];
  3164. var tm15 = this.m[15];
  3165. var om0 = other.m[0];
  3166. var om1 = other.m[1];
  3167. var om2 = other.m[2];
  3168. var om3 = other.m[3];
  3169. var om4 = other.m[4];
  3170. var om5 = other.m[5];
  3171. var om6 = other.m[6];
  3172. var om7 = other.m[7];
  3173. var om8 = other.m[8];
  3174. var om9 = other.m[9];
  3175. var om10 = other.m[10];
  3176. var om11 = other.m[11];
  3177. var om12 = other.m[12];
  3178. var om13 = other.m[13];
  3179. var om14 = other.m[14];
  3180. var om15 = other.m[15];
  3181. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  3182. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  3183. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3184. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3185. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3186. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3187. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3188. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3189. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3190. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3191. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3192. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3193. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3194. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3195. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3196. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3197. return this;
  3198. };
  3199. /**
  3200. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3201. */
  3202. Matrix.prototype.equals = function (value) {
  3203. return value &&
  3204. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3205. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3206. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3207. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3208. };
  3209. /**
  3210. * Returns a new Matrix from the current Matrix.
  3211. */
  3212. Matrix.prototype.clone = function () {
  3213. 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]);
  3214. };
  3215. /**
  3216. * Returns the string "Matrix"
  3217. */
  3218. Matrix.prototype.getClassName = function () {
  3219. return "Matrix";
  3220. };
  3221. /**
  3222. * Returns the Matrix hash code.
  3223. */
  3224. Matrix.prototype.getHashCode = function () {
  3225. var hash = this.m[0] || 0;
  3226. for (var i = 1; i < 16; i++) {
  3227. hash = (hash * 397) ^ (this.m[i] || 0);
  3228. }
  3229. return hash;
  3230. };
  3231. /**
  3232. * Decomposes the current Matrix into :
  3233. * - a scale vector3 passed as a reference to update,
  3234. * - a rotation quaternion passed as a reference to update,
  3235. * - a translation vector3 passed as a reference to update.
  3236. * Returns the boolean `true`.
  3237. */
  3238. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3239. translation.x = this.m[12];
  3240. translation.y = this.m[13];
  3241. translation.z = this.m[14];
  3242. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3243. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3244. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3245. if (this.determinant() <= 0) {
  3246. scale.y *= -1;
  3247. }
  3248. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3249. rotation.x = 0;
  3250. rotation.y = 0;
  3251. rotation.z = 0;
  3252. rotation.w = 1;
  3253. return false;
  3254. }
  3255. 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]);
  3256. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3257. return true;
  3258. };
  3259. /**
  3260. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3261. */
  3262. Matrix.prototype.getRotationMatrix = function () {
  3263. var result = Matrix.Identity();
  3264. this.getRotationMatrixToRef(result);
  3265. return result;
  3266. };
  3267. /**
  3268. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3269. * Returns the current Matrix.
  3270. */
  3271. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3272. var m = this.m;
  3273. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3274. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3275. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3276. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3277. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3278. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3279. 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);
  3280. return this;
  3281. };
  3282. // Statics
  3283. /**
  3284. * Returns a new Matrix set from the starting index of the passed array.
  3285. */
  3286. Matrix.FromArray = function (array, offset) {
  3287. var result = new Matrix();
  3288. if (!offset) {
  3289. offset = 0;
  3290. }
  3291. Matrix.FromArrayToRef(array, offset, result);
  3292. return result;
  3293. };
  3294. /**
  3295. * Sets the passed "result" matrix from the starting index of the passed array.
  3296. */
  3297. Matrix.FromArrayToRef = function (array, offset, result) {
  3298. for (var index = 0; index < 16; index++) {
  3299. result.m[index] = array[index + offset];
  3300. }
  3301. result._markAsUpdated();
  3302. };
  3303. /**
  3304. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3305. */
  3306. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3307. for (var index = 0; index < 16; index++) {
  3308. result.m[index] = array[index + offset] * scale;
  3309. }
  3310. result._markAsUpdated();
  3311. };
  3312. /**
  3313. * Sets the passed matrix "result" with the 16 passed floats.
  3314. */
  3315. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3316. result.m[0] = initialM11;
  3317. result.m[1] = initialM12;
  3318. result.m[2] = initialM13;
  3319. result.m[3] = initialM14;
  3320. result.m[4] = initialM21;
  3321. result.m[5] = initialM22;
  3322. result.m[6] = initialM23;
  3323. result.m[7] = initialM24;
  3324. result.m[8] = initialM31;
  3325. result.m[9] = initialM32;
  3326. result.m[10] = initialM33;
  3327. result.m[11] = initialM34;
  3328. result.m[12] = initialM41;
  3329. result.m[13] = initialM42;
  3330. result.m[14] = initialM43;
  3331. result.m[15] = initialM44;
  3332. result._markAsUpdated();
  3333. };
  3334. /**
  3335. * Returns the index-th row of the current matrix as a new Vector4.
  3336. */
  3337. Matrix.prototype.getRow = function (index) {
  3338. if (index < 0 || index > 3) {
  3339. return null;
  3340. }
  3341. var i = index * 4;
  3342. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3343. };
  3344. /**
  3345. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3346. * Returns the updated Matrix.
  3347. */
  3348. Matrix.prototype.setRow = function (index, row) {
  3349. if (index < 0 || index > 3) {
  3350. return this;
  3351. }
  3352. var i = index * 4;
  3353. this.m[i + 0] = row.x;
  3354. this.m[i + 1] = row.y;
  3355. this.m[i + 2] = row.z;
  3356. this.m[i + 3] = row.w;
  3357. this._markAsUpdated();
  3358. return this;
  3359. };
  3360. /**
  3361. * Compute the transpose of the matrix.
  3362. * Returns a new Matrix.
  3363. */
  3364. Matrix.prototype.transpose = function () {
  3365. return Matrix.Transpose(this);
  3366. };
  3367. /**
  3368. * Compute the transpose of the matrix.
  3369. * Returns the current matrix.
  3370. */
  3371. Matrix.prototype.transposeToRef = function (result) {
  3372. Matrix.TransposeToRef(this, result);
  3373. return this;
  3374. };
  3375. /**
  3376. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3377. * Returns the updated Matrix.
  3378. */
  3379. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3380. if (index < 0 || index > 3) {
  3381. return this;
  3382. }
  3383. var i = index * 4;
  3384. this.m[i + 0] = x;
  3385. this.m[i + 1] = y;
  3386. this.m[i + 2] = z;
  3387. this.m[i + 3] = w;
  3388. this._markAsUpdated();
  3389. return this;
  3390. };
  3391. Object.defineProperty(Matrix, "IdentityReadOnly", {
  3392. /**
  3393. * Static identity matrix to be used as readonly matrix
  3394. * Must not be updated.
  3395. */
  3396. get: function () {
  3397. return Matrix._identityReadOnly;
  3398. },
  3399. enumerable: true,
  3400. configurable: true
  3401. });
  3402. /**
  3403. * Returns a new Matrix set from the 16 passed floats.
  3404. */
  3405. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3406. var result = new Matrix();
  3407. result.m[0] = initialM11;
  3408. result.m[1] = initialM12;
  3409. result.m[2] = initialM13;
  3410. result.m[3] = initialM14;
  3411. result.m[4] = initialM21;
  3412. result.m[5] = initialM22;
  3413. result.m[6] = initialM23;
  3414. result.m[7] = initialM24;
  3415. result.m[8] = initialM31;
  3416. result.m[9] = initialM32;
  3417. result.m[10] = initialM33;
  3418. result.m[11] = initialM34;
  3419. result.m[12] = initialM41;
  3420. result.m[13] = initialM42;
  3421. result.m[14] = initialM43;
  3422. result.m[15] = initialM44;
  3423. return result;
  3424. };
  3425. /**
  3426. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3427. */
  3428. Matrix.Compose = function (scale, rotation, translation) {
  3429. var result = Matrix.Identity();
  3430. Matrix.ComposeToRef(scale, rotation, translation, result);
  3431. return result;
  3432. };
  3433. /**
  3434. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3435. */
  3436. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3437. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3438. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3439. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3440. result.setTranslation(translation);
  3441. };
  3442. /**
  3443. * Returns a new indentity Matrix.
  3444. */
  3445. Matrix.Identity = function () {
  3446. 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);
  3447. };
  3448. /**
  3449. * Sets the passed "result" as an identity matrix.
  3450. */
  3451. Matrix.IdentityToRef = function (result) {
  3452. 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);
  3453. };
  3454. /**
  3455. * Returns a new zero Matrix.
  3456. */
  3457. Matrix.Zero = function () {
  3458. 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);
  3459. };
  3460. /**
  3461. * Returns a new rotation matrix for "angle" radians around the X axis.
  3462. */
  3463. Matrix.RotationX = function (angle) {
  3464. var result = new Matrix();
  3465. Matrix.RotationXToRef(angle, result);
  3466. return result;
  3467. };
  3468. /**
  3469. * Returns a new Matrix as the passed inverted one.
  3470. */
  3471. Matrix.Invert = function (source) {
  3472. var result = new Matrix();
  3473. source.invertToRef(result);
  3474. return result;
  3475. };
  3476. /**
  3477. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3478. */
  3479. Matrix.RotationXToRef = function (angle, result) {
  3480. var s = Math.sin(angle);
  3481. var c = Math.cos(angle);
  3482. result.m[0] = 1.0;
  3483. result.m[15] = 1.0;
  3484. result.m[5] = c;
  3485. result.m[10] = c;
  3486. result.m[9] = -s;
  3487. result.m[6] = s;
  3488. result.m[1] = 0.0;
  3489. result.m[2] = 0.0;
  3490. result.m[3] = 0.0;
  3491. result.m[4] = 0.0;
  3492. result.m[7] = 0.0;
  3493. result.m[8] = 0.0;
  3494. result.m[11] = 0.0;
  3495. result.m[12] = 0.0;
  3496. result.m[13] = 0.0;
  3497. result.m[14] = 0.0;
  3498. result._markAsUpdated();
  3499. };
  3500. /**
  3501. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3502. */
  3503. Matrix.RotationY = function (angle) {
  3504. var result = new Matrix();
  3505. Matrix.RotationYToRef(angle, result);
  3506. return result;
  3507. };
  3508. /**
  3509. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3510. */
  3511. Matrix.RotationYToRef = function (angle, result) {
  3512. var s = Math.sin(angle);
  3513. var c = Math.cos(angle);
  3514. result.m[5] = 1.0;
  3515. result.m[15] = 1.0;
  3516. result.m[0] = c;
  3517. result.m[2] = -s;
  3518. result.m[8] = s;
  3519. result.m[10] = c;
  3520. result.m[1] = 0.0;
  3521. result.m[3] = 0.0;
  3522. result.m[4] = 0.0;
  3523. result.m[6] = 0.0;
  3524. result.m[7] = 0.0;
  3525. result.m[9] = 0.0;
  3526. result.m[11] = 0.0;
  3527. result.m[12] = 0.0;
  3528. result.m[13] = 0.0;
  3529. result.m[14] = 0.0;
  3530. result._markAsUpdated();
  3531. };
  3532. /**
  3533. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3534. */
  3535. Matrix.RotationZ = function (angle) {
  3536. var result = new Matrix();
  3537. Matrix.RotationZToRef(angle, result);
  3538. return result;
  3539. };
  3540. /**
  3541. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3542. */
  3543. Matrix.RotationZToRef = function (angle, result) {
  3544. var s = Math.sin(angle);
  3545. var c = Math.cos(angle);
  3546. result.m[10] = 1.0;
  3547. result.m[15] = 1.0;
  3548. result.m[0] = c;
  3549. result.m[1] = s;
  3550. result.m[4] = -s;
  3551. result.m[5] = c;
  3552. result.m[2] = 0.0;
  3553. result.m[3] = 0.0;
  3554. result.m[6] = 0.0;
  3555. result.m[7] = 0.0;
  3556. result.m[8] = 0.0;
  3557. result.m[9] = 0.0;
  3558. result.m[11] = 0.0;
  3559. result.m[12] = 0.0;
  3560. result.m[13] = 0.0;
  3561. result.m[14] = 0.0;
  3562. result._markAsUpdated();
  3563. };
  3564. /**
  3565. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3566. */
  3567. Matrix.RotationAxis = function (axis, angle) {
  3568. var result = Matrix.Zero();
  3569. Matrix.RotationAxisToRef(axis, angle, result);
  3570. return result;
  3571. };
  3572. /**
  3573. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3574. */
  3575. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3576. var s = Math.sin(-angle);
  3577. var c = Math.cos(-angle);
  3578. var c1 = 1 - c;
  3579. axis.normalize();
  3580. result.m[0] = (axis.x * axis.x) * c1 + c;
  3581. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3582. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3583. result.m[3] = 0.0;
  3584. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3585. result.m[5] = (axis.y * axis.y) * c1 + c;
  3586. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3587. result.m[7] = 0.0;
  3588. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3589. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3590. result.m[10] = (axis.z * axis.z) * c1 + c;
  3591. result.m[11] = 0.0;
  3592. result.m[15] = 1.0;
  3593. result._markAsUpdated();
  3594. };
  3595. /**
  3596. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3597. */
  3598. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3599. var result = new Matrix();
  3600. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3601. return result;
  3602. };
  3603. /**
  3604. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3605. */
  3606. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3607. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3608. this._tempQuaternion.toRotationMatrix(result);
  3609. };
  3610. /**
  3611. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3612. */
  3613. Matrix.Scaling = function (x, y, z) {
  3614. var result = Matrix.Zero();
  3615. Matrix.ScalingToRef(x, y, z, result);
  3616. return result;
  3617. };
  3618. /**
  3619. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3620. */
  3621. Matrix.ScalingToRef = function (x, y, z, result) {
  3622. result.m[0] = x;
  3623. result.m[1] = 0.0;
  3624. result.m[2] = 0.0;
  3625. result.m[3] = 0.0;
  3626. result.m[4] = 0.0;
  3627. result.m[5] = y;
  3628. result.m[6] = 0.0;
  3629. result.m[7] = 0.0;
  3630. result.m[8] = 0.0;
  3631. result.m[9] = 0.0;
  3632. result.m[10] = z;
  3633. result.m[11] = 0.0;
  3634. result.m[12] = 0.0;
  3635. result.m[13] = 0.0;
  3636. result.m[14] = 0.0;
  3637. result.m[15] = 1.0;
  3638. result._markAsUpdated();
  3639. };
  3640. /**
  3641. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3642. */
  3643. Matrix.Translation = function (x, y, z) {
  3644. var result = Matrix.Identity();
  3645. Matrix.TranslationToRef(x, y, z, result);
  3646. return result;
  3647. };
  3648. /**
  3649. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3650. */
  3651. Matrix.TranslationToRef = function (x, y, z, result) {
  3652. 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);
  3653. };
  3654. /**
  3655. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3656. */
  3657. Matrix.Lerp = function (startValue, endValue, gradient) {
  3658. var result = Matrix.Zero();
  3659. for (var index = 0; index < 16; index++) {
  3660. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3661. }
  3662. result._markAsUpdated();
  3663. return result;
  3664. };
  3665. /**
  3666. * Returns a new Matrix whose values are computed by :
  3667. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3668. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3669. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3670. */
  3671. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3672. var startScale = new Vector3(0, 0, 0);
  3673. var startRotation = new Quaternion();
  3674. var startTranslation = new Vector3(0, 0, 0);
  3675. startValue.decompose(startScale, startRotation, startTranslation);
  3676. var endScale = new Vector3(0, 0, 0);
  3677. var endRotation = new Quaternion();
  3678. var endTranslation = new Vector3(0, 0, 0);
  3679. endValue.decompose(endScale, endRotation, endTranslation);
  3680. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3681. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3682. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3683. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3684. };
  3685. /**
  3686. * 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".
  3687. * This methods works for a Left-Handed system.
  3688. */
  3689. Matrix.LookAtLH = function (eye, target, up) {
  3690. var result = Matrix.Zero();
  3691. Matrix.LookAtLHToRef(eye, target, up, result);
  3692. return result;
  3693. };
  3694. /**
  3695. * 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".
  3696. * This methods works for a Left-Handed system.
  3697. */
  3698. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3699. // Z axis
  3700. target.subtractToRef(eye, this._zAxis);
  3701. this._zAxis.normalize();
  3702. // X axis
  3703. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3704. if (this._xAxis.lengthSquared() === 0) {
  3705. this._xAxis.x = 1.0;
  3706. }
  3707. else {
  3708. this._xAxis.normalize();
  3709. }
  3710. // Y axis
  3711. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3712. this._yAxis.normalize();
  3713. // Eye angles
  3714. var ex = -Vector3.Dot(this._xAxis, eye);
  3715. var ey = -Vector3.Dot(this._yAxis, eye);
  3716. var ez = -Vector3.Dot(this._zAxis, eye);
  3717. 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);
  3718. };
  3719. /**
  3720. * 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".
  3721. * This methods works for a Right-Handed system.
  3722. */
  3723. Matrix.LookAtRH = function (eye, target, up) {
  3724. var result = Matrix.Zero();
  3725. Matrix.LookAtRHToRef(eye, target, up, result);
  3726. return result;
  3727. };
  3728. /**
  3729. * 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".
  3730. * This methods works for a Left-Handed system.
  3731. */
  3732. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3733. // Z axis
  3734. eye.subtractToRef(target, this._zAxis);
  3735. this._zAxis.normalize();
  3736. // X axis
  3737. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3738. if (this._xAxis.lengthSquared() === 0) {
  3739. this._xAxis.x = 1.0;
  3740. }
  3741. else {
  3742. this._xAxis.normalize();
  3743. }
  3744. // Y axis
  3745. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3746. this._yAxis.normalize();
  3747. // Eye angles
  3748. var ex = -Vector3.Dot(this._xAxis, eye);
  3749. var ey = -Vector3.Dot(this._yAxis, eye);
  3750. var ez = -Vector3.Dot(this._zAxis, eye);
  3751. 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);
  3752. };
  3753. /**
  3754. * 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.
  3755. */
  3756. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3757. var matrix = Matrix.Zero();
  3758. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3759. return matrix;
  3760. };
  3761. /**
  3762. * 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.
  3763. */
  3764. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3765. var n = znear;
  3766. var f = zfar;
  3767. var a = 2.0 / width;
  3768. var b = 2.0 / height;
  3769. var c = 2.0 / (f - n);
  3770. var d = -(f + n) / (f - n);
  3771. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  3772. };
  3773. /**
  3774. * 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.
  3775. */
  3776. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3777. var matrix = Matrix.Zero();
  3778. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3779. return matrix;
  3780. };
  3781. /**
  3782. * 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.
  3783. */
  3784. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3785. var n = znear;
  3786. var f = zfar;
  3787. var a = 2.0 / (right - left);
  3788. var b = 2.0 / (top - bottom);
  3789. var c = 2.0 / (f - n);
  3790. var d = -(f + n) / (f - n);
  3791. var i0 = (left + right) / (left - right);
  3792. var i1 = (top + bottom) / (bottom - top);
  3793. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  3794. };
  3795. /**
  3796. * 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.
  3797. */
  3798. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3799. var matrix = Matrix.Zero();
  3800. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3801. return matrix;
  3802. };
  3803. /**
  3804. * 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.
  3805. */
  3806. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3807. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3808. result.m[10] *= -1.0;
  3809. };
  3810. /**
  3811. * 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.
  3812. */
  3813. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3814. var matrix = Matrix.Zero();
  3815. var n = znear;
  3816. var f = zfar;
  3817. var a = 2.0 * n / width;
  3818. var b = 2.0 * n / height;
  3819. var c = (f + n) / (f - n);
  3820. var d = -2.0 * f * n / (f - n);
  3821. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  3822. return matrix;
  3823. };
  3824. /**
  3825. * 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.
  3826. */
  3827. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3828. var matrix = Matrix.Zero();
  3829. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3830. return matrix;
  3831. };
  3832. /**
  3833. * 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.
  3834. */
  3835. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3836. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3837. var n = znear;
  3838. var f = zfar;
  3839. var t = 1.0 / (Math.tan(fov * 0.5));
  3840. var a = isVerticalFovFixed ? (t / aspect) : t;
  3841. var b = isVerticalFovFixed ? t : (t * aspect);
  3842. var c = (f + n) / (f - n);
  3843. var d = -2.0 * f * n / (f - n);
  3844. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  3845. };
  3846. /**
  3847. * 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.
  3848. */
  3849. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3850. var matrix = Matrix.Zero();
  3851. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3852. return matrix;
  3853. };
  3854. /**
  3855. * 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.
  3856. */
  3857. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3858. //alternatively this could be expressed as:
  3859. // m = PerspectiveFovLHToRef
  3860. // m[10] *= -1.0;
  3861. // m[11] *= -1.0;
  3862. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3863. var n = znear;
  3864. var f = zfar;
  3865. var t = 1.0 / (Math.tan(fov * 0.5));
  3866. var a = isVerticalFovFixed ? (t / aspect) : t;
  3867. var b = isVerticalFovFixed ? t : (t * aspect);
  3868. var c = -(f + n) / (f - n);
  3869. var d = -2 * f * n / (f - n);
  3870. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  3871. };
  3872. /**
  3873. * 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.
  3874. */
  3875. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3876. if (rightHanded === void 0) { rightHanded = false; }
  3877. var rightHandedFactor = rightHanded ? -1 : 1;
  3878. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3879. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3880. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3881. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3882. var xScale = 2.0 / (leftTan + rightTan);
  3883. var yScale = 2.0 / (upTan + downTan);
  3884. result.m[0] = xScale;
  3885. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3886. result.m[5] = yScale;
  3887. result.m[6] = result.m[7] = 0.0;
  3888. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3889. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3890. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3891. result.m[10] = -zfar / (znear - zfar);
  3892. result.m[11] = 1.0 * rightHandedFactor;
  3893. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3894. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3895. // result.m[14] = (znear * zfar) / (znear - zfar);
  3896. result._markAsUpdated();
  3897. };
  3898. /**
  3899. * Returns the final transformation matrix : world * view * projection * viewport
  3900. */
  3901. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3902. var cw = viewport.width;
  3903. var ch = viewport.height;
  3904. var cx = viewport.x;
  3905. var cy = viewport.y;
  3906. 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);
  3907. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3908. };
  3909. /**
  3910. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3911. */
  3912. Matrix.GetAsMatrix2x2 = function (matrix) {
  3913. return new Float32Array([
  3914. matrix.m[0], matrix.m[1],
  3915. matrix.m[4], matrix.m[5]
  3916. ]);
  3917. };
  3918. /**
  3919. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3920. */
  3921. Matrix.GetAsMatrix3x3 = function (matrix) {
  3922. return new Float32Array([
  3923. matrix.m[0], matrix.m[1], matrix.m[2],
  3924. matrix.m[4], matrix.m[5], matrix.m[6],
  3925. matrix.m[8], matrix.m[9], matrix.m[10]
  3926. ]);
  3927. };
  3928. /**
  3929. * Compute the transpose of the passed Matrix.
  3930. * Returns a new Matrix.
  3931. */
  3932. Matrix.Transpose = function (matrix) {
  3933. var result = new Matrix();
  3934. Matrix.TransposeToRef(matrix, result);
  3935. return result;
  3936. };
  3937. /**
  3938. * Compute the transpose of the passed Matrix and store it in the result matrix.
  3939. */
  3940. Matrix.TransposeToRef = function (matrix, result) {
  3941. result.m[0] = matrix.m[0];
  3942. result.m[1] = matrix.m[4];
  3943. result.m[2] = matrix.m[8];
  3944. result.m[3] = matrix.m[12];
  3945. result.m[4] = matrix.m[1];
  3946. result.m[5] = matrix.m[5];
  3947. result.m[6] = matrix.m[9];
  3948. result.m[7] = matrix.m[13];
  3949. result.m[8] = matrix.m[2];
  3950. result.m[9] = matrix.m[6];
  3951. result.m[10] = matrix.m[10];
  3952. result.m[11] = matrix.m[14];
  3953. result.m[12] = matrix.m[3];
  3954. result.m[13] = matrix.m[7];
  3955. result.m[14] = matrix.m[11];
  3956. result.m[15] = matrix.m[15];
  3957. };
  3958. /**
  3959. * Returns a new Matrix as the reflection matrix across the passed plane.
  3960. */
  3961. Matrix.Reflection = function (plane) {
  3962. var matrix = new Matrix();
  3963. Matrix.ReflectionToRef(plane, matrix);
  3964. return matrix;
  3965. };
  3966. /**
  3967. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3968. */
  3969. Matrix.ReflectionToRef = function (plane, result) {
  3970. plane.normalize();
  3971. var x = plane.normal.x;
  3972. var y = plane.normal.y;
  3973. var z = plane.normal.z;
  3974. var temp = -2 * x;
  3975. var temp2 = -2 * y;
  3976. var temp3 = -2 * z;
  3977. result.m[0] = (temp * x) + 1;
  3978. result.m[1] = temp2 * x;
  3979. result.m[2] = temp3 * x;
  3980. result.m[3] = 0.0;
  3981. result.m[4] = temp * y;
  3982. result.m[5] = (temp2 * y) + 1;
  3983. result.m[6] = temp3 * y;
  3984. result.m[7] = 0.0;
  3985. result.m[8] = temp * z;
  3986. result.m[9] = temp2 * z;
  3987. result.m[10] = (temp3 * z) + 1;
  3988. result.m[11] = 0.0;
  3989. result.m[12] = temp * plane.d;
  3990. result.m[13] = temp2 * plane.d;
  3991. result.m[14] = temp3 * plane.d;
  3992. result.m[15] = 1.0;
  3993. result._markAsUpdated();
  3994. };
  3995. /**
  3996. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3997. */
  3998. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3999. result.m[0] = xaxis.x;
  4000. result.m[1] = xaxis.y;
  4001. result.m[2] = xaxis.z;
  4002. result.m[3] = 0.0;
  4003. result.m[4] = yaxis.x;
  4004. result.m[5] = yaxis.y;
  4005. result.m[6] = yaxis.z;
  4006. result.m[7] = 0.0;
  4007. result.m[8] = zaxis.x;
  4008. result.m[9] = zaxis.y;
  4009. result.m[10] = zaxis.z;
  4010. result.m[11] = 0.0;
  4011. result.m[12] = 0.0;
  4012. result.m[13] = 0.0;
  4013. result.m[14] = 0.0;
  4014. result.m[15] = 1.0;
  4015. result._markAsUpdated();
  4016. };
  4017. /**
  4018. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  4019. */
  4020. Matrix.FromQuaternionToRef = function (quat, result) {
  4021. var xx = quat.x * quat.x;
  4022. var yy = quat.y * quat.y;
  4023. var zz = quat.z * quat.z;
  4024. var xy = quat.x * quat.y;
  4025. var zw = quat.z * quat.w;
  4026. var zx = quat.z * quat.x;
  4027. var yw = quat.y * quat.w;
  4028. var yz = quat.y * quat.z;
  4029. var xw = quat.x * quat.w;
  4030. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4031. result.m[1] = 2.0 * (xy + zw);
  4032. result.m[2] = 2.0 * (zx - yw);
  4033. result.m[3] = 0.0;
  4034. result.m[4] = 2.0 * (xy - zw);
  4035. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4036. result.m[6] = 2.0 * (yz + xw);
  4037. result.m[7] = 0.0;
  4038. result.m[8] = 2.0 * (zx + yw);
  4039. result.m[9] = 2.0 * (yz - xw);
  4040. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4041. result.m[11] = 0.0;
  4042. result.m[12] = 0.0;
  4043. result.m[13] = 0.0;
  4044. result.m[14] = 0.0;
  4045. result.m[15] = 1.0;
  4046. result._markAsUpdated();
  4047. };
  4048. Matrix._tempQuaternion = new Quaternion();
  4049. Matrix._xAxis = Vector3.Zero();
  4050. Matrix._yAxis = Vector3.Zero();
  4051. Matrix._zAxis = Vector3.Zero();
  4052. Matrix._updateFlagSeed = 0;
  4053. Matrix._identityReadOnly = Matrix.Identity();
  4054. return Matrix;
  4055. }());
  4056. BABYLON.Matrix = Matrix;
  4057. var Plane = /** @class */ (function () {
  4058. /**
  4059. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  4060. */
  4061. function Plane(a, b, c, d) {
  4062. this.normal = new Vector3(a, b, c);
  4063. this.d = d;
  4064. }
  4065. /**
  4066. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4067. */
  4068. Plane.prototype.asArray = function () {
  4069. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4070. };
  4071. // Methods
  4072. /**
  4073. * Returns a new plane copied from the current Plane.
  4074. */
  4075. Plane.prototype.clone = function () {
  4076. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4077. };
  4078. /**
  4079. * Returns the string "Plane".
  4080. */
  4081. Plane.prototype.getClassName = function () {
  4082. return "Plane";
  4083. };
  4084. /**
  4085. * Returns the Plane hash code.
  4086. */
  4087. Plane.prototype.getHashCode = function () {
  4088. var hash = this.normal.getHashCode();
  4089. hash = (hash * 397) ^ (this.d || 0);
  4090. return hash;
  4091. };
  4092. /**
  4093. * Normalize the current Plane in place.
  4094. * Returns the updated Plane.
  4095. */
  4096. Plane.prototype.normalize = function () {
  4097. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4098. var magnitude = 0.0;
  4099. if (norm !== 0) {
  4100. magnitude = 1.0 / norm;
  4101. }
  4102. this.normal.x *= magnitude;
  4103. this.normal.y *= magnitude;
  4104. this.normal.z *= magnitude;
  4105. this.d *= magnitude;
  4106. return this;
  4107. };
  4108. /**
  4109. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4110. */
  4111. Plane.prototype.transform = function (transformation) {
  4112. var transposedMatrix = Matrix.Transpose(transformation);
  4113. var x = this.normal.x;
  4114. var y = this.normal.y;
  4115. var z = this.normal.z;
  4116. var d = this.d;
  4117. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4118. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4119. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4120. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4121. return new Plane(normalX, normalY, normalZ, finalD);
  4122. };
  4123. /**
  4124. * Returns the dot product (float) of the point coordinates and the plane normal.
  4125. */
  4126. Plane.prototype.dotCoordinate = function (point) {
  4127. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4128. };
  4129. /**
  4130. * Updates the current Plane from the plane defined by the three passed points.
  4131. * Returns the updated Plane.
  4132. */
  4133. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4134. var x1 = point2.x - point1.x;
  4135. var y1 = point2.y - point1.y;
  4136. var z1 = point2.z - point1.z;
  4137. var x2 = point3.x - point1.x;
  4138. var y2 = point3.y - point1.y;
  4139. var z2 = point3.z - point1.z;
  4140. var yz = (y1 * z2) - (z1 * y2);
  4141. var xz = (z1 * x2) - (x1 * z2);
  4142. var xy = (x1 * y2) - (y1 * x2);
  4143. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  4144. var invPyth;
  4145. if (pyth !== 0) {
  4146. invPyth = 1.0 / pyth;
  4147. }
  4148. else {
  4149. invPyth = 0.0;
  4150. }
  4151. this.normal.x = yz * invPyth;
  4152. this.normal.y = xz * invPyth;
  4153. this.normal.z = xy * invPyth;
  4154. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  4155. return this;
  4156. };
  4157. /**
  4158. * Boolean : True is the vector "direction" is the same side than the plane normal.
  4159. */
  4160. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  4161. var dot = Vector3.Dot(this.normal, direction);
  4162. return (dot <= epsilon);
  4163. };
  4164. /**
  4165. * Returns the signed distance (float) from the passed point to the Plane.
  4166. */
  4167. Plane.prototype.signedDistanceTo = function (point) {
  4168. return Vector3.Dot(point, this.normal) + this.d;
  4169. };
  4170. // Statics
  4171. /**
  4172. * Returns a new Plane from the passed array.
  4173. */
  4174. Plane.FromArray = function (array) {
  4175. return new Plane(array[0], array[1], array[2], array[3]);
  4176. };
  4177. /**
  4178. * Returns a new Plane defined by the three passed points.
  4179. */
  4180. Plane.FromPoints = function (point1, point2, point3) {
  4181. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4182. result.copyFromPoints(point1, point2, point3);
  4183. return result;
  4184. };
  4185. /**
  4186. * Returns a new Plane the normal vector to this plane at the passed origin point.
  4187. * Note : the vector "normal" is updated because normalized.
  4188. */
  4189. Plane.FromPositionAndNormal = function (origin, normal) {
  4190. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4191. normal.normalize();
  4192. result.normal = normal;
  4193. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4194. return result;
  4195. };
  4196. /**
  4197. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  4198. */
  4199. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  4200. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4201. return Vector3.Dot(point, normal) + d;
  4202. };
  4203. return Plane;
  4204. }());
  4205. BABYLON.Plane = Plane;
  4206. var Viewport = /** @class */ (function () {
  4207. /**
  4208. * Creates a Viewport object located at (x, y) and sized (width, height).
  4209. */
  4210. function Viewport(x, y, width, height) {
  4211. this.x = x;
  4212. this.y = y;
  4213. this.width = width;
  4214. this.height = height;
  4215. }
  4216. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4217. if (renderWidthOrEngine.getRenderWidth) {
  4218. var engine = renderWidthOrEngine;
  4219. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4220. }
  4221. var renderWidth = renderWidthOrEngine;
  4222. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4223. };
  4224. /**
  4225. * Returns a new Viewport copied from the current one.
  4226. */
  4227. Viewport.prototype.clone = function () {
  4228. return new Viewport(this.x, this.y, this.width, this.height);
  4229. };
  4230. return Viewport;
  4231. }());
  4232. BABYLON.Viewport = Viewport;
  4233. var Frustum = /** @class */ (function () {
  4234. function Frustum() {
  4235. }
  4236. /**
  4237. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4238. */
  4239. Frustum.GetPlanes = function (transform) {
  4240. var frustumPlanes = [];
  4241. for (var index = 0; index < 6; index++) {
  4242. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4243. }
  4244. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4245. return frustumPlanes;
  4246. };
  4247. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  4248. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  4249. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  4250. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  4251. frustumPlane.d = transform.m[15] + transform.m[14];
  4252. frustumPlane.normalize();
  4253. };
  4254. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  4255. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  4256. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  4257. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  4258. frustumPlane.d = transform.m[15] - transform.m[14];
  4259. frustumPlane.normalize();
  4260. };
  4261. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  4262. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  4263. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  4264. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  4265. frustumPlane.d = transform.m[15] + transform.m[12];
  4266. frustumPlane.normalize();
  4267. };
  4268. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  4269. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  4270. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  4271. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  4272. frustumPlane.d = transform.m[15] - transform.m[12];
  4273. frustumPlane.normalize();
  4274. };
  4275. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  4276. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  4277. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  4278. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  4279. frustumPlane.d = transform.m[15] - transform.m[13];
  4280. frustumPlane.normalize();
  4281. };
  4282. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  4283. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  4284. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  4285. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  4286. frustumPlane.d = transform.m[15] + transform.m[13];
  4287. frustumPlane.normalize();
  4288. };
  4289. /**
  4290. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4291. */
  4292. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4293. // Near
  4294. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  4295. // Far
  4296. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  4297. // Left
  4298. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  4299. // Right
  4300. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  4301. // Top
  4302. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  4303. // Bottom
  4304. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  4305. };
  4306. return Frustum;
  4307. }());
  4308. BABYLON.Frustum = Frustum;
  4309. var Space;
  4310. (function (Space) {
  4311. Space[Space["LOCAL"] = 0] = "LOCAL";
  4312. Space[Space["WORLD"] = 1] = "WORLD";
  4313. Space[Space["BONE"] = 2] = "BONE";
  4314. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4315. var Axis = /** @class */ (function () {
  4316. function Axis() {
  4317. }
  4318. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4319. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4320. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4321. return Axis;
  4322. }());
  4323. BABYLON.Axis = Axis;
  4324. ;
  4325. var BezierCurve = /** @class */ (function () {
  4326. function BezierCurve() {
  4327. }
  4328. /**
  4329. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4330. */
  4331. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4332. // Extract X (which is equal to time here)
  4333. var f0 = 1 - 3 * x2 + 3 * x1;
  4334. var f1 = 3 * x2 - 6 * x1;
  4335. var f2 = 3 * x1;
  4336. var refinedT = t;
  4337. for (var i = 0; i < 5; i++) {
  4338. var refinedT2 = refinedT * refinedT;
  4339. var refinedT3 = refinedT2 * refinedT;
  4340. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4341. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4342. refinedT -= (x - t) * slope;
  4343. refinedT = Math.min(1, Math.max(0, refinedT));
  4344. }
  4345. // Resolve cubic bezier for the given x
  4346. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4347. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4348. Math.pow(refinedT, 3);
  4349. };
  4350. return BezierCurve;
  4351. }());
  4352. BABYLON.BezierCurve = BezierCurve;
  4353. var Orientation;
  4354. (function (Orientation) {
  4355. Orientation[Orientation["CW"] = 0] = "CW";
  4356. Orientation[Orientation["CCW"] = 1] = "CCW";
  4357. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4358. var Angle = /** @class */ (function () {
  4359. /**
  4360. * Creates an Angle object of "radians" radians (float).
  4361. */
  4362. function Angle(radians) {
  4363. var _this = this;
  4364. /**
  4365. * Returns the Angle value in degrees (float).
  4366. */
  4367. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4368. /**
  4369. * Returns the Angle value in radians (float).
  4370. */
  4371. this.radians = function () { return _this._radians; };
  4372. this._radians = radians;
  4373. if (this._radians < 0.0)
  4374. this._radians += (2.0 * Math.PI);
  4375. }
  4376. /**
  4377. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4378. */
  4379. Angle.BetweenTwoPoints = function (a, b) {
  4380. var delta = b.subtract(a);
  4381. var theta = Math.atan2(delta.y, delta.x);
  4382. return new Angle(theta);
  4383. };
  4384. /**
  4385. * Returns a new Angle object from the passed float in radians.
  4386. */
  4387. Angle.FromRadians = function (radians) {
  4388. return new Angle(radians);
  4389. };
  4390. /**
  4391. * Returns a new Angle object from the passed float in degrees.
  4392. */
  4393. Angle.FromDegrees = function (degrees) {
  4394. return new Angle(degrees * Math.PI / 180.0);
  4395. };
  4396. return Angle;
  4397. }());
  4398. BABYLON.Angle = Angle;
  4399. var Arc2 = /** @class */ (function () {
  4400. /**
  4401. * Creates an Arc object from the three passed points : start, middle and end.
  4402. */
  4403. function Arc2(startPoint, midPoint, endPoint) {
  4404. this.startPoint = startPoint;
  4405. this.midPoint = midPoint;
  4406. this.endPoint = endPoint;
  4407. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4408. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4409. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4410. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4411. 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);
  4412. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4413. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4414. var a1 = this.startAngle.degrees();
  4415. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4416. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4417. // angles correction
  4418. if (a2 - a1 > +180.0)
  4419. a2 -= 360.0;
  4420. if (a2 - a1 < -180.0)
  4421. a2 += 360.0;
  4422. if (a3 - a2 > +180.0)
  4423. a3 -= 360.0;
  4424. if (a3 - a2 < -180.0)
  4425. a3 += 360.0;
  4426. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4427. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4428. }
  4429. return Arc2;
  4430. }());
  4431. BABYLON.Arc2 = Arc2;
  4432. var Path2 = /** @class */ (function () {
  4433. /**
  4434. * Creates a Path2 object from the starting 2D coordinates x and y.
  4435. */
  4436. function Path2(x, y) {
  4437. this._points = new Array();
  4438. this._length = 0.0;
  4439. this.closed = false;
  4440. this._points.push(new Vector2(x, y));
  4441. }
  4442. /**
  4443. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4444. * Returns the updated Path2.
  4445. */
  4446. Path2.prototype.addLineTo = function (x, y) {
  4447. if (this.closed) {
  4448. //Tools.Error("cannot add lines to closed paths");
  4449. return this;
  4450. }
  4451. var newPoint = new Vector2(x, y);
  4452. var previousPoint = this._points[this._points.length - 1];
  4453. this._points.push(newPoint);
  4454. this._length += newPoint.subtract(previousPoint).length();
  4455. return this;
  4456. };
  4457. /**
  4458. * 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.
  4459. * Returns the updated Path2.
  4460. */
  4461. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4462. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4463. if (this.closed) {
  4464. //Tools.Error("cannot add arcs to closed paths");
  4465. return this;
  4466. }
  4467. var startPoint = this._points[this._points.length - 1];
  4468. var midPoint = new Vector2(midX, midY);
  4469. var endPoint = new Vector2(endX, endY);
  4470. var arc = new Arc2(startPoint, midPoint, endPoint);
  4471. var increment = arc.angle.radians() / numberOfSegments;
  4472. if (arc.orientation === Orientation.CW)
  4473. increment *= -1;
  4474. var currentAngle = arc.startAngle.radians() + increment;
  4475. for (var i = 0; i < numberOfSegments; i++) {
  4476. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4477. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4478. this.addLineTo(x, y);
  4479. currentAngle += increment;
  4480. }
  4481. return this;
  4482. };
  4483. /**
  4484. * Closes the Path2.
  4485. * Returns the Path2.
  4486. */
  4487. Path2.prototype.close = function () {
  4488. this.closed = true;
  4489. return this;
  4490. };
  4491. /**
  4492. * Returns the Path2 total length (float).
  4493. */
  4494. Path2.prototype.length = function () {
  4495. var result = this._length;
  4496. if (!this.closed) {
  4497. var lastPoint = this._points[this._points.length - 1];
  4498. var firstPoint = this._points[0];
  4499. result += (firstPoint.subtract(lastPoint).length());
  4500. }
  4501. return result;
  4502. };
  4503. /**
  4504. * Returns the Path2 internal array of points.
  4505. */
  4506. Path2.prototype.getPoints = function () {
  4507. return this._points;
  4508. };
  4509. /**
  4510. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4511. */
  4512. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4513. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4514. //Tools.Error("normalized length position should be between 0 and 1.");
  4515. return Vector2.Zero();
  4516. }
  4517. var lengthPosition = normalizedLengthPosition * this.length();
  4518. var previousOffset = 0;
  4519. for (var i = 0; i < this._points.length; i++) {
  4520. var j = (i + 1) % this._points.length;
  4521. var a = this._points[i];
  4522. var b = this._points[j];
  4523. var bToA = b.subtract(a);
  4524. var nextOffset = (bToA.length() + previousOffset);
  4525. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4526. var dir = bToA.normalize();
  4527. var localOffset = lengthPosition - previousOffset;
  4528. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4529. }
  4530. previousOffset = nextOffset;
  4531. }
  4532. //Tools.Error("internal error");
  4533. return Vector2.Zero();
  4534. };
  4535. /**
  4536. * Returns a new Path2 starting at the coordinates (x, y).
  4537. */
  4538. Path2.StartingAt = function (x, y) {
  4539. return new Path2(x, y);
  4540. };
  4541. return Path2;
  4542. }());
  4543. BABYLON.Path2 = Path2;
  4544. var Path3D = /** @class */ (function () {
  4545. /**
  4546. * new Path3D(path, normal, raw)
  4547. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4548. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4549. * path : an array of Vector3, the curve axis of the Path3D
  4550. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4551. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4552. */
  4553. function Path3D(path, firstNormal, raw) {
  4554. if (firstNormal === void 0) { firstNormal = null; }
  4555. this.path = path;
  4556. this._curve = new Array();
  4557. this._distances = new Array();
  4558. this._tangents = new Array();
  4559. this._normals = new Array();
  4560. this._binormals = new Array();
  4561. for (var p = 0; p < path.length; p++) {
  4562. this._curve[p] = path[p].clone(); // hard copy
  4563. }
  4564. this._raw = raw || false;
  4565. this._compute(firstNormal);
  4566. }
  4567. /**
  4568. * Returns the Path3D array of successive Vector3 designing its curve.
  4569. */
  4570. Path3D.prototype.getCurve = function () {
  4571. return this._curve;
  4572. };
  4573. /**
  4574. * Returns an array populated with tangent vectors on each Path3D curve point.
  4575. */
  4576. Path3D.prototype.getTangents = function () {
  4577. return this._tangents;
  4578. };
  4579. /**
  4580. * Returns an array populated with normal vectors on each Path3D curve point.
  4581. */
  4582. Path3D.prototype.getNormals = function () {
  4583. return this._normals;
  4584. };
  4585. /**
  4586. * Returns an array populated with binormal vectors on each Path3D curve point.
  4587. */
  4588. Path3D.prototype.getBinormals = function () {
  4589. return this._binormals;
  4590. };
  4591. /**
  4592. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4593. */
  4594. Path3D.prototype.getDistances = function () {
  4595. return this._distances;
  4596. };
  4597. /**
  4598. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4599. * Returns the same object updated.
  4600. */
  4601. Path3D.prototype.update = function (path, firstNormal) {
  4602. if (firstNormal === void 0) { firstNormal = null; }
  4603. for (var p = 0; p < path.length; p++) {
  4604. this._curve[p].x = path[p].x;
  4605. this._curve[p].y = path[p].y;
  4606. this._curve[p].z = path[p].z;
  4607. }
  4608. this._compute(firstNormal);
  4609. return this;
  4610. };
  4611. // private function compute() : computes tangents, normals and binormals
  4612. Path3D.prototype._compute = function (firstNormal) {
  4613. var l = this._curve.length;
  4614. // first and last tangents
  4615. this._tangents[0] = this._getFirstNonNullVector(0);
  4616. if (!this._raw) {
  4617. this._tangents[0].normalize();
  4618. }
  4619. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4620. if (!this._raw) {
  4621. this._tangents[l - 1].normalize();
  4622. }
  4623. // normals and binormals at first point : arbitrary vector with _normalVector()
  4624. var tg0 = this._tangents[0];
  4625. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4626. this._normals[0] = pp0;
  4627. if (!this._raw) {
  4628. this._normals[0].normalize();
  4629. }
  4630. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4631. if (!this._raw) {
  4632. this._binormals[0].normalize();
  4633. }
  4634. this._distances[0] = 0.0;
  4635. // normals and binormals : next points
  4636. var prev; // previous vector (segment)
  4637. var cur; // current vector (segment)
  4638. var curTang; // current tangent
  4639. // previous normal
  4640. var prevBinor; // previous binormal
  4641. for (var i = 1; i < l; i++) {
  4642. // tangents
  4643. prev = this._getLastNonNullVector(i);
  4644. if (i < l - 1) {
  4645. cur = this._getFirstNonNullVector(i);
  4646. this._tangents[i] = prev.add(cur);
  4647. this._tangents[i].normalize();
  4648. }
  4649. this._distances[i] = this._distances[i - 1] + prev.length();
  4650. // normals and binormals
  4651. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4652. curTang = this._tangents[i];
  4653. prevBinor = this._binormals[i - 1];
  4654. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4655. if (!this._raw) {
  4656. this._normals[i].normalize();
  4657. }
  4658. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4659. if (!this._raw) {
  4660. this._binormals[i].normalize();
  4661. }
  4662. }
  4663. };
  4664. // private function getFirstNonNullVector(index)
  4665. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4666. Path3D.prototype._getFirstNonNullVector = function (index) {
  4667. var i = 1;
  4668. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4669. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4670. i++;
  4671. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4672. }
  4673. return nNVector;
  4674. };
  4675. // private function getLastNonNullVector(index)
  4676. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4677. Path3D.prototype._getLastNonNullVector = function (index) {
  4678. var i = 1;
  4679. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4680. while (nLVector.length() === 0 && index > i + 1) {
  4681. i++;
  4682. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4683. }
  4684. return nLVector;
  4685. };
  4686. // private function normalVector(v0, vt, va) :
  4687. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4688. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4689. Path3D.prototype._normalVector = function (v0, vt, va) {
  4690. var normal0;
  4691. var tgl = vt.length();
  4692. if (tgl === 0.0) {
  4693. tgl = 1.0;
  4694. }
  4695. if (va === undefined || va === null) {
  4696. var point;
  4697. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4698. point = new Vector3(0.0, -1.0, 0.0);
  4699. }
  4700. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4701. point = new Vector3(1.0, 0.0, 0.0);
  4702. }
  4703. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4704. point = new Vector3(0.0, 0.0, 1.0);
  4705. }
  4706. else {
  4707. point = Vector3.Zero();
  4708. }
  4709. normal0 = Vector3.Cross(vt, point);
  4710. }
  4711. else {
  4712. normal0 = Vector3.Cross(vt, va);
  4713. Vector3.CrossToRef(normal0, vt, normal0);
  4714. }
  4715. normal0.normalize();
  4716. return normal0;
  4717. };
  4718. return Path3D;
  4719. }());
  4720. BABYLON.Path3D = Path3D;
  4721. var Curve3 = /** @class */ (function () {
  4722. /**
  4723. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4724. * A Curve3 is designed from a series of successive Vector3.
  4725. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4726. */
  4727. function Curve3(points) {
  4728. this._length = 0.0;
  4729. this._points = points;
  4730. this._length = this._computeLength(points);
  4731. }
  4732. /**
  4733. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4734. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4735. * @param v1 (Vector3) the control point
  4736. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4737. * @param nbPoints (integer) the wanted number of points in the curve
  4738. */
  4739. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4740. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4741. var bez = new Array();
  4742. var equation = function (t, val0, val1, val2) {
  4743. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4744. return res;
  4745. };
  4746. for (var i = 0; i <= nbPoints; i++) {
  4747. 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)));
  4748. }
  4749. return new Curve3(bez);
  4750. };
  4751. /**
  4752. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4753. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4754. * @param v1 (Vector3) the first control point
  4755. * @param v2 (Vector3) the second control point
  4756. * @param v3 (Vector3) the end point of the Cubic Bezier
  4757. * @param nbPoints (integer) the wanted number of points in the curve
  4758. */
  4759. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4760. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4761. var bez = new Array();
  4762. var equation = function (t, val0, val1, val2, val3) {
  4763. 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;
  4764. return res;
  4765. };
  4766. for (var i = 0; i <= nbPoints; i++) {
  4767. 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)));
  4768. }
  4769. return new Curve3(bez);
  4770. };
  4771. /**
  4772. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4773. * @param p1 (Vector3) the origin point of the Hermite Spline
  4774. * @param t1 (Vector3) the tangent vector at the origin point
  4775. * @param p2 (Vector3) the end point of the Hermite Spline
  4776. * @param t2 (Vector3) the tangent vector at the end point
  4777. * @param nbPoints (integer) the wanted number of points in the curve
  4778. */
  4779. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4780. var hermite = new Array();
  4781. var step = 1.0 / nbPoints;
  4782. for (var i = 0; i <= nbPoints; i++) {
  4783. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4784. }
  4785. return new Curve3(hermite);
  4786. };
  4787. /**
  4788. * Returns a Curve3 object along a CatmullRom Spline curve :
  4789. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4790. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4791. */
  4792. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4793. var totalPoints = new Array();
  4794. totalPoints.push(points[0].clone());
  4795. Array.prototype.push.apply(totalPoints, points);
  4796. totalPoints.push(points[points.length - 1].clone());
  4797. var catmullRom = new Array();
  4798. var step = 1.0 / nbPoints;
  4799. var amount = 0.0;
  4800. for (var i = 0; i < totalPoints.length - 3; i++) {
  4801. amount = 0;
  4802. for (var c = 0; c < nbPoints; c++) {
  4803. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4804. amount += step;
  4805. }
  4806. }
  4807. i--;
  4808. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4809. return new Curve3(catmullRom);
  4810. };
  4811. /**
  4812. * Returns the Curve3 stored array of successive Vector3
  4813. */
  4814. Curve3.prototype.getPoints = function () {
  4815. return this._points;
  4816. };
  4817. /**
  4818. * Returns the computed length (float) of the curve.
  4819. */
  4820. Curve3.prototype.length = function () {
  4821. return this._length;
  4822. };
  4823. /**
  4824. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4825. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4826. * curveA and curveB keep unchanged.
  4827. */
  4828. Curve3.prototype.continue = function (curve) {
  4829. var lastPoint = this._points[this._points.length - 1];
  4830. var continuedPoints = this._points.slice();
  4831. var curvePoints = curve.getPoints();
  4832. for (var i = 1; i < curvePoints.length; i++) {
  4833. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4834. }
  4835. var continuedCurve = new Curve3(continuedPoints);
  4836. return continuedCurve;
  4837. };
  4838. Curve3.prototype._computeLength = function (path) {
  4839. var l = 0;
  4840. for (var i = 1; i < path.length; i++) {
  4841. l += (path[i].subtract(path[i - 1])).length();
  4842. }
  4843. return l;
  4844. };
  4845. return Curve3;
  4846. }());
  4847. BABYLON.Curve3 = Curve3;
  4848. // Vertex formats
  4849. var PositionNormalVertex = /** @class */ (function () {
  4850. function PositionNormalVertex(position, normal) {
  4851. if (position === void 0) { position = Vector3.Zero(); }
  4852. if (normal === void 0) { normal = Vector3.Up(); }
  4853. this.position = position;
  4854. this.normal = normal;
  4855. }
  4856. PositionNormalVertex.prototype.clone = function () {
  4857. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4858. };
  4859. return PositionNormalVertex;
  4860. }());
  4861. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4862. var PositionNormalTextureVertex = /** @class */ (function () {
  4863. function PositionNormalTextureVertex(position, normal, uv) {
  4864. if (position === void 0) { position = Vector3.Zero(); }
  4865. if (normal === void 0) { normal = Vector3.Up(); }
  4866. if (uv === void 0) { uv = Vector2.Zero(); }
  4867. this.position = position;
  4868. this.normal = normal;
  4869. this.uv = uv;
  4870. }
  4871. PositionNormalTextureVertex.prototype.clone = function () {
  4872. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4873. };
  4874. return PositionNormalTextureVertex;
  4875. }());
  4876. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4877. // Temporary pre-allocated objects for engine internal use
  4878. // usage in any internal function :
  4879. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4880. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4881. var Tmp = /** @class */ (function () {
  4882. function Tmp() {
  4883. }
  4884. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4885. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4886. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4887. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4888. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4889. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4890. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4891. Matrix.Zero(), Matrix.Zero(),
  4892. Matrix.Zero(), Matrix.Zero(),
  4893. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4894. return Tmp;
  4895. }());
  4896. BABYLON.Tmp = Tmp;
  4897. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4898. var MathTmp = /** @class */ (function () {
  4899. function MathTmp() {
  4900. }
  4901. MathTmp.Vector3 = [Vector3.Zero()];
  4902. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4903. MathTmp.Quaternion = [Quaternion.Zero()];
  4904. return MathTmp;
  4905. }());
  4906. })(BABYLON || (BABYLON = {}));
  4907. //# sourceMappingURL=babylon.math.js.map
  4908. var BABYLON;
  4909. (function (BABYLON) {
  4910. var Scalar = /** @class */ (function () {
  4911. function Scalar() {
  4912. }
  4913. /**
  4914. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4915. */
  4916. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4917. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4918. var num = a - b;
  4919. return -epsilon <= num && num <= epsilon;
  4920. };
  4921. /**
  4922. * Returns a string : the upper case translation of the number i to hexadecimal.
  4923. */
  4924. Scalar.ToHex = function (i) {
  4925. var str = i.toString(16);
  4926. if (i <= 15) {
  4927. return ("0" + str).toUpperCase();
  4928. }
  4929. return str.toUpperCase();
  4930. };
  4931. /**
  4932. * Returns -1 if value is negative and +1 is value is positive.
  4933. * Returns the value itself if it's equal to zero.
  4934. */
  4935. Scalar.Sign = function (value) {
  4936. value = +value; // convert to a number
  4937. if (value === 0 || isNaN(value))
  4938. return value;
  4939. return value > 0 ? 1 : -1;
  4940. };
  4941. /**
  4942. * Returns the value itself if it's between min and max.
  4943. * Returns min if the value is lower than min.
  4944. * Returns max if the value is greater than max.
  4945. */
  4946. Scalar.Clamp = function (value, min, max) {
  4947. if (min === void 0) { min = 0; }
  4948. if (max === void 0) { max = 1; }
  4949. return Math.min(max, Math.max(min, value));
  4950. };
  4951. /**
  4952. * Returns the log2 of value.
  4953. */
  4954. Scalar.Log2 = function (value) {
  4955. return Math.log(value) * Math.LOG2E;
  4956. };
  4957. /**
  4958. * Loops the value, so that it is never larger than length and never smaller than 0.
  4959. *
  4960. * This is similar to the modulo operator but it works with floating point numbers.
  4961. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  4962. * With t = 5 and length = 2.5, the result would be 0.0.
  4963. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  4964. */
  4965. Scalar.Repeat = function (value, length) {
  4966. return value - Math.floor(value / length) * length;
  4967. };
  4968. /**
  4969. * Normalize the value between 0.0 and 1.0 using min and max values
  4970. */
  4971. Scalar.Normalize = function (value, min, max) {
  4972. return (value - min) / (max - min);
  4973. };
  4974. /**
  4975. * Denormalize the value from 0.0 and 1.0 using min and max values
  4976. */
  4977. Scalar.Denormalize = function (normalized, min, max) {
  4978. return (normalized * (max - min) + min);
  4979. };
  4980. /**
  4981. * Calculates the shortest difference between two given angles given in degrees.
  4982. */
  4983. Scalar.DeltaAngle = function (current, target) {
  4984. var num = Scalar.Repeat(target - current, 360.0);
  4985. if (num > 180.0) {
  4986. num -= 360.0;
  4987. }
  4988. return num;
  4989. };
  4990. /**
  4991. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  4992. *
  4993. * The returned value will move back and forth between 0 and length
  4994. */
  4995. Scalar.PingPong = function (tx, length) {
  4996. var t = Scalar.Repeat(tx, length * 2.0);
  4997. return length - Math.abs(t - length);
  4998. };
  4999. /**
  5000. * Interpolates between min and max with smoothing at the limits.
  5001. *
  5002. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  5003. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  5004. */
  5005. Scalar.SmoothStep = function (from, to, tx) {
  5006. var t = Scalar.Clamp(tx);
  5007. t = -2.0 * t * t * t + 3.0 * t * t;
  5008. return to * t + from * (1.0 - t);
  5009. };
  5010. /**
  5011. * Moves a value current towards target.
  5012. *
  5013. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  5014. * Negative values of maxDelta pushes the value away from target.
  5015. */
  5016. Scalar.MoveTowards = function (current, target, maxDelta) {
  5017. var result = 0;
  5018. if (Math.abs(target - current) <= maxDelta) {
  5019. result = target;
  5020. }
  5021. else {
  5022. result = current + Scalar.Sign(target - current) * maxDelta;
  5023. }
  5024. return result;
  5025. };
  5026. /**
  5027. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5028. *
  5029. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  5030. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  5031. */
  5032. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  5033. var num = Scalar.DeltaAngle(current, target);
  5034. var result = 0;
  5035. if (-maxDelta < num && num < maxDelta) {
  5036. result = target;
  5037. }
  5038. else {
  5039. target = current + num;
  5040. result = Scalar.MoveTowards(current, target, maxDelta);
  5041. }
  5042. return result;
  5043. };
  5044. /**
  5045. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  5046. */
  5047. Scalar.Lerp = function (start, end, amount) {
  5048. return start + ((end - start) * amount);
  5049. };
  5050. /**
  5051. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5052. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  5053. */
  5054. Scalar.LerpAngle = function (start, end, amount) {
  5055. var num = Scalar.Repeat(end - start, 360.0);
  5056. if (num > 180.0) {
  5057. num -= 360.0;
  5058. }
  5059. return start + num * Scalar.Clamp(amount);
  5060. };
  5061. /**
  5062. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  5063. */
  5064. Scalar.InverseLerp = function (a, b, value) {
  5065. var result = 0;
  5066. if (a != b) {
  5067. result = Scalar.Clamp((value - a) / (b - a));
  5068. }
  5069. else {
  5070. result = 0.0;
  5071. }
  5072. return result;
  5073. };
  5074. /**
  5075. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5076. */
  5077. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5078. var squared = amount * amount;
  5079. var cubed = amount * squared;
  5080. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5081. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5082. var part3 = (cubed - (2.0 * squared)) + amount;
  5083. var part4 = cubed - squared;
  5084. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  5085. };
  5086. /**
  5087. * Returns a random float number between and min and max values
  5088. */
  5089. Scalar.RandomRange = function (min, max) {
  5090. if (min === max)
  5091. return min;
  5092. return ((Math.random() * (max - min)) + min);
  5093. };
  5094. /**
  5095. * This function returns percentage of a number in a given range.
  5096. *
  5097. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5098. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5099. */
  5100. Scalar.RangeToPercent = function (number, min, max) {
  5101. return ((number - min) / (max - min));
  5102. };
  5103. /**
  5104. * This function returns number that corresponds to the percentage in a given range.
  5105. *
  5106. * PercentToRange(0.34,0,100) will return 34.
  5107. */
  5108. Scalar.PercentToRange = function (percent, min, max) {
  5109. return ((max - min) * percent + min);
  5110. };
  5111. /**
  5112. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  5113. * @param angle The angle to normalize in radian.
  5114. * @return The converted angle.
  5115. */
  5116. Scalar.NormalizeRadians = function (angle) {
  5117. // More precise but slower version kept for reference.
  5118. // angle = angle % Tools.TwoPi;
  5119. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  5120. //if (angle > Math.PI) {
  5121. // angle -= Tools.TwoPi;
  5122. //}
  5123. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  5124. return angle;
  5125. };
  5126. /**
  5127. * Two pi constants convenient for computation.
  5128. */
  5129. Scalar.TwoPi = Math.PI * 2;
  5130. return Scalar;
  5131. }());
  5132. BABYLON.Scalar = Scalar;
  5133. })(BABYLON || (BABYLON = {}));
  5134. //# sourceMappingURL=babylon.math.scalar.js.map
  5135. //# sourceMappingURL=babylon.mixins.js.map
  5136. var BABYLON;
  5137. (function (BABYLON) {
  5138. var __decoratorInitialStore = {};
  5139. var __mergedStore = {};
  5140. var _copySource = function (creationFunction, source, instanciate) {
  5141. var destination = creationFunction();
  5142. // Tags
  5143. if (BABYLON.Tags) {
  5144. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5145. }
  5146. var classStore = getMergedStore(destination);
  5147. // Properties
  5148. for (var property in classStore) {
  5149. var propertyDescriptor = classStore[property];
  5150. var sourceProperty = source[property];
  5151. var propertyType = propertyDescriptor.type;
  5152. if (sourceProperty !== undefined && sourceProperty !== null) {
  5153. switch (propertyType) {
  5154. case 0: // Value
  5155. case 6:// Mesh reference
  5156. destination[property] = sourceProperty;
  5157. break;
  5158. case 1:// Texture
  5159. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  5160. break;
  5161. case 2: // Color3
  5162. case 3: // FresnelParameters
  5163. case 4: // Vector2
  5164. case 5: // Vector3
  5165. case 7:// Color Curves
  5166. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  5167. break;
  5168. }
  5169. }
  5170. }
  5171. return destination;
  5172. };
  5173. function getDirectStore(target) {
  5174. var classKey = target.getClassName();
  5175. if (!__decoratorInitialStore[classKey]) {
  5176. __decoratorInitialStore[classKey] = {};
  5177. }
  5178. return __decoratorInitialStore[classKey];
  5179. }
  5180. /**
  5181. * Return the list of properties flagged as serializable
  5182. * @param target: host object
  5183. */
  5184. function getMergedStore(target) {
  5185. var classKey = target.getClassName();
  5186. if (__mergedStore[classKey]) {
  5187. return __mergedStore[classKey];
  5188. }
  5189. __mergedStore[classKey] = {};
  5190. var store = __mergedStore[classKey];
  5191. var currentTarget = target;
  5192. var currentKey = classKey;
  5193. while (currentKey) {
  5194. var initialStore = __decoratorInitialStore[currentKey];
  5195. for (var property in initialStore) {
  5196. store[property] = initialStore[property];
  5197. }
  5198. var parent_1 = void 0;
  5199. var done = false;
  5200. do {
  5201. parent_1 = Object.getPrototypeOf(currentTarget);
  5202. if (!parent_1.getClassName) {
  5203. done = true;
  5204. break;
  5205. }
  5206. if (parent_1.getClassName() !== currentKey) {
  5207. break;
  5208. }
  5209. currentTarget = parent_1;
  5210. } while (parent_1);
  5211. if (done) {
  5212. break;
  5213. }
  5214. currentKey = parent_1.getClassName();
  5215. currentTarget = parent_1;
  5216. }
  5217. return store;
  5218. }
  5219. function generateSerializableMember(type, sourceName) {
  5220. return function (target, propertyKey) {
  5221. var classStore = getDirectStore(target);
  5222. if (!classStore[propertyKey]) {
  5223. classStore[propertyKey] = { type: type, sourceName: sourceName };
  5224. }
  5225. };
  5226. }
  5227. function generateExpandMember(setCallback, targetKey) {
  5228. if (targetKey === void 0) { targetKey = null; }
  5229. return function (target, propertyKey) {
  5230. var key = targetKey || ("_" + propertyKey);
  5231. Object.defineProperty(target, propertyKey, {
  5232. get: function () {
  5233. return this[key];
  5234. },
  5235. set: function (value) {
  5236. if (this[key] === value) {
  5237. return;
  5238. }
  5239. this[key] = value;
  5240. target[setCallback].apply(this);
  5241. },
  5242. enumerable: true,
  5243. configurable: true
  5244. });
  5245. };
  5246. }
  5247. function expandToProperty(callback, targetKey) {
  5248. if (targetKey === void 0) { targetKey = null; }
  5249. return generateExpandMember(callback, targetKey);
  5250. }
  5251. BABYLON.expandToProperty = expandToProperty;
  5252. function serialize(sourceName) {
  5253. return generateSerializableMember(0, sourceName); // value member
  5254. }
  5255. BABYLON.serialize = serialize;
  5256. function serializeAsTexture(sourceName) {
  5257. return generateSerializableMember(1, sourceName); // texture member
  5258. }
  5259. BABYLON.serializeAsTexture = serializeAsTexture;
  5260. function serializeAsColor3(sourceName) {
  5261. return generateSerializableMember(2, sourceName); // color3 member
  5262. }
  5263. BABYLON.serializeAsColor3 = serializeAsColor3;
  5264. function serializeAsFresnelParameters(sourceName) {
  5265. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5266. }
  5267. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5268. function serializeAsVector2(sourceName) {
  5269. return generateSerializableMember(4, sourceName); // vector2 member
  5270. }
  5271. BABYLON.serializeAsVector2 = serializeAsVector2;
  5272. function serializeAsVector3(sourceName) {
  5273. return generateSerializableMember(5, sourceName); // vector3 member
  5274. }
  5275. BABYLON.serializeAsVector3 = serializeAsVector3;
  5276. function serializeAsMeshReference(sourceName) {
  5277. return generateSerializableMember(6, sourceName); // mesh reference member
  5278. }
  5279. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5280. function serializeAsColorCurves(sourceName) {
  5281. return generateSerializableMember(7, sourceName); // color curves
  5282. }
  5283. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5284. function serializeAsColor4(sourceName) {
  5285. return generateSerializableMember(8, sourceName); // color 4
  5286. }
  5287. BABYLON.serializeAsColor4 = serializeAsColor4;
  5288. function serializeAsImageProcessingConfiguration(sourceName) {
  5289. return generateSerializableMember(9, sourceName); // image processing
  5290. }
  5291. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5292. var SerializationHelper = /** @class */ (function () {
  5293. function SerializationHelper() {
  5294. }
  5295. SerializationHelper.Serialize = function (entity, serializationObject) {
  5296. if (!serializationObject) {
  5297. serializationObject = {};
  5298. }
  5299. // Tags
  5300. if (BABYLON.Tags) {
  5301. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5302. }
  5303. var serializedProperties = getMergedStore(entity);
  5304. // Properties
  5305. for (var property in serializedProperties) {
  5306. var propertyDescriptor = serializedProperties[property];
  5307. var targetPropertyName = propertyDescriptor.sourceName || property;
  5308. var propertyType = propertyDescriptor.type;
  5309. var sourceProperty = entity[property];
  5310. if (sourceProperty !== undefined && sourceProperty !== null) {
  5311. switch (propertyType) {
  5312. case 0:// Value
  5313. serializationObject[targetPropertyName] = sourceProperty;
  5314. break;
  5315. case 1:// Texture
  5316. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5317. break;
  5318. case 2:// Color3
  5319. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5320. break;
  5321. case 3:// FresnelParameters
  5322. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5323. break;
  5324. case 4:// Vector2
  5325. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5326. break;
  5327. case 5:// Vector3
  5328. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5329. break;
  5330. case 6:// Mesh reference
  5331. serializationObject[targetPropertyName] = sourceProperty.id;
  5332. break;
  5333. case 7:// Color Curves
  5334. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5335. break;
  5336. case 8:// Color 4
  5337. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5338. break;
  5339. case 9:// Image Processing
  5340. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5341. break;
  5342. }
  5343. }
  5344. }
  5345. return serializationObject;
  5346. };
  5347. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5348. if (rootUrl === void 0) { rootUrl = null; }
  5349. var destination = creationFunction();
  5350. if (!rootUrl) {
  5351. rootUrl = "";
  5352. }
  5353. // Tags
  5354. if (BABYLON.Tags) {
  5355. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5356. }
  5357. var classStore = getMergedStore(destination);
  5358. // Properties
  5359. for (var property in classStore) {
  5360. var propertyDescriptor = classStore[property];
  5361. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5362. var propertyType = propertyDescriptor.type;
  5363. if (sourceProperty !== undefined && sourceProperty !== null) {
  5364. var dest = destination;
  5365. switch (propertyType) {
  5366. case 0:// Value
  5367. dest[property] = sourceProperty;
  5368. break;
  5369. case 1:// Texture
  5370. if (scene) {
  5371. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5372. }
  5373. break;
  5374. case 2:// Color3
  5375. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  5376. break;
  5377. case 3:// FresnelParameters
  5378. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5379. break;
  5380. case 4:// Vector2
  5381. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5382. break;
  5383. case 5:// Vector3
  5384. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5385. break;
  5386. case 6:// Mesh reference
  5387. if (scene) {
  5388. dest[property] = scene.getLastMeshByID(sourceProperty);
  5389. }
  5390. break;
  5391. case 7:// Color Curves
  5392. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5393. break;
  5394. case 8:// Color 4
  5395. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  5396. break;
  5397. case 9:// Image Processing
  5398. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5399. break;
  5400. }
  5401. }
  5402. }
  5403. return destination;
  5404. };
  5405. SerializationHelper.Clone = function (creationFunction, source) {
  5406. return _copySource(creationFunction, source, false);
  5407. };
  5408. SerializationHelper.Instanciate = function (creationFunction, source) {
  5409. return _copySource(creationFunction, source, true);
  5410. };
  5411. return SerializationHelper;
  5412. }());
  5413. BABYLON.SerializationHelper = SerializationHelper;
  5414. })(BABYLON || (BABYLON = {}));
  5415. //# sourceMappingURL=babylon.decorators.js.map
  5416. var BABYLON;
  5417. (function (BABYLON) {
  5418. /**
  5419. * A class serves as a medium between the observable and its observers
  5420. */
  5421. var EventState = /** @class */ (function () {
  5422. /**
  5423. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5424. */
  5425. function EventState(mask, skipNextObservers, target, currentTarget) {
  5426. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5427. this.initalize(mask, skipNextObservers, target, currentTarget);
  5428. }
  5429. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  5430. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5431. this.mask = mask;
  5432. this.skipNextObservers = skipNextObservers;
  5433. this.target = target;
  5434. this.currentTarget = currentTarget;
  5435. return this;
  5436. };
  5437. return EventState;
  5438. }());
  5439. BABYLON.EventState = EventState;
  5440. /**
  5441. * Represent an Observer registered to a given Observable object.
  5442. */
  5443. var Observer = /** @class */ (function () {
  5444. function Observer(callback, mask, scope) {
  5445. if (scope === void 0) { scope = null; }
  5446. this.callback = callback;
  5447. this.mask = mask;
  5448. this.scope = scope;
  5449. }
  5450. return Observer;
  5451. }());
  5452. BABYLON.Observer = Observer;
  5453. /**
  5454. * Represent a list of observers registered to multiple Observables object.
  5455. */
  5456. var MultiObserver = /** @class */ (function () {
  5457. function MultiObserver() {
  5458. }
  5459. MultiObserver.prototype.dispose = function () {
  5460. if (this._observers && this._observables) {
  5461. for (var index = 0; index < this._observers.length; index++) {
  5462. this._observables[index].remove(this._observers[index]);
  5463. }
  5464. }
  5465. this._observers = null;
  5466. this._observables = null;
  5467. };
  5468. MultiObserver.Watch = function (observables, callback, mask, scope) {
  5469. if (mask === void 0) { mask = -1; }
  5470. if (scope === void 0) { scope = null; }
  5471. var result = new MultiObserver();
  5472. result._observers = new Array();
  5473. result._observables = observables;
  5474. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  5475. var observable = observables_1[_i];
  5476. var observer = observable.add(callback, mask, false, scope);
  5477. if (observer) {
  5478. result._observers.push(observer);
  5479. }
  5480. }
  5481. return result;
  5482. };
  5483. return MultiObserver;
  5484. }());
  5485. BABYLON.MultiObserver = MultiObserver;
  5486. /**
  5487. * The Observable class is a simple implementation of the Observable pattern.
  5488. * 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.
  5489. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5490. * 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).
  5491. * 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.
  5492. */
  5493. var Observable = /** @class */ (function () {
  5494. function Observable(onObserverAdded) {
  5495. this._observers = new Array();
  5496. this._eventState = new EventState(0);
  5497. if (onObserverAdded) {
  5498. this._onObserverAdded = onObserverAdded;
  5499. }
  5500. }
  5501. /**
  5502. * Create a new Observer with the specified callback
  5503. * @param callback the callback that will be executed for that Observer
  5504. * @param mask the mask used to filter observers
  5505. * @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.
  5506. * @param scope optional scope for the callback to be called from
  5507. */
  5508. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  5509. if (mask === void 0) { mask = -1; }
  5510. if (insertFirst === void 0) { insertFirst = false; }
  5511. if (scope === void 0) { scope = null; }
  5512. if (!callback) {
  5513. return null;
  5514. }
  5515. var observer = new Observer(callback, mask, scope);
  5516. if (insertFirst) {
  5517. this._observers.unshift(observer);
  5518. }
  5519. else {
  5520. this._observers.push(observer);
  5521. }
  5522. if (this._onObserverAdded) {
  5523. this._onObserverAdded(observer);
  5524. }
  5525. return observer;
  5526. };
  5527. /**
  5528. * Remove an Observer from the Observable object
  5529. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5530. */
  5531. Observable.prototype.remove = function (observer) {
  5532. if (!observer) {
  5533. return false;
  5534. }
  5535. var index = this._observers.indexOf(observer);
  5536. if (index !== -1) {
  5537. this._observers.splice(index, 1);
  5538. return true;
  5539. }
  5540. return false;
  5541. };
  5542. /**
  5543. * Remove a callback from the Observable object
  5544. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5545. */
  5546. Observable.prototype.removeCallback = function (callback) {
  5547. for (var index = 0; index < this._observers.length; index++) {
  5548. if (this._observers[index].callback === callback) {
  5549. this._observers.splice(index, 1);
  5550. return true;
  5551. }
  5552. }
  5553. return false;
  5554. };
  5555. /**
  5556. * Notify all Observers by calling their respective callback with the given data
  5557. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5558. * @param eventData
  5559. * @param mask
  5560. */
  5561. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  5562. if (mask === void 0) { mask = -1; }
  5563. if (!this._observers.length) {
  5564. return true;
  5565. }
  5566. var state = this._eventState;
  5567. state.mask = mask;
  5568. state.target = target;
  5569. state.currentTarget = currentTarget;
  5570. state.skipNextObservers = false;
  5571. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5572. var obs = _a[_i];
  5573. if (obs.mask & mask) {
  5574. if (obs.scope) {
  5575. obs.callback.apply(obs.scope, [eventData, state]);
  5576. }
  5577. else {
  5578. obs.callback(eventData, state);
  5579. }
  5580. }
  5581. if (state.skipNextObservers) {
  5582. return false;
  5583. }
  5584. }
  5585. return true;
  5586. };
  5587. /**
  5588. * Notify a specific observer
  5589. * @param eventData
  5590. * @param mask
  5591. */
  5592. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  5593. if (mask === void 0) { mask = -1; }
  5594. var state = this._eventState;
  5595. state.mask = mask;
  5596. state.skipNextObservers = false;
  5597. observer.callback(eventData, state);
  5598. };
  5599. /**
  5600. * return true is the Observable has at least one Observer registered
  5601. */
  5602. Observable.prototype.hasObservers = function () {
  5603. return this._observers.length > 0;
  5604. };
  5605. /**
  5606. * Clear the list of observers
  5607. */
  5608. Observable.prototype.clear = function () {
  5609. this._observers = new Array();
  5610. this._onObserverAdded = null;
  5611. };
  5612. /**
  5613. * Clone the current observable
  5614. */
  5615. Observable.prototype.clone = function () {
  5616. var result = new Observable();
  5617. result._observers = this._observers.slice(0);
  5618. return result;
  5619. };
  5620. /**
  5621. * Does this observable handles observer registered with a given mask
  5622. * @param {number} trigger - the mask to be tested
  5623. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5624. **/
  5625. Observable.prototype.hasSpecificMask = function (mask) {
  5626. if (mask === void 0) { mask = -1; }
  5627. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5628. var obs = _a[_i];
  5629. if (obs.mask & mask || obs.mask === mask) {
  5630. return true;
  5631. }
  5632. }
  5633. return false;
  5634. };
  5635. return Observable;
  5636. }());
  5637. BABYLON.Observable = Observable;
  5638. })(BABYLON || (BABYLON = {}));
  5639. //# sourceMappingURL=babylon.observable.js.map
  5640. var BABYLON;
  5641. (function (BABYLON) {
  5642. var SmartArray = /** @class */ (function () {
  5643. function SmartArray(capacity) {
  5644. this.length = 0;
  5645. this.data = new Array(capacity);
  5646. this._id = SmartArray._GlobalId++;
  5647. }
  5648. SmartArray.prototype.push = function (value) {
  5649. this.data[this.length++] = value;
  5650. if (this.length > this.data.length) {
  5651. this.data.length *= 2;
  5652. }
  5653. };
  5654. SmartArray.prototype.forEach = function (func) {
  5655. for (var index = 0; index < this.length; index++) {
  5656. func(this.data[index]);
  5657. }
  5658. };
  5659. SmartArray.prototype.sort = function (compareFn) {
  5660. this.data.sort(compareFn);
  5661. };
  5662. SmartArray.prototype.reset = function () {
  5663. this.length = 0;
  5664. };
  5665. SmartArray.prototype.dispose = function () {
  5666. this.reset();
  5667. if (this.data) {
  5668. this.data.length = 0;
  5669. this.data = [];
  5670. }
  5671. };
  5672. SmartArray.prototype.concat = function (array) {
  5673. if (array.length === 0) {
  5674. return;
  5675. }
  5676. if (this.length + array.length > this.data.length) {
  5677. this.data.length = (this.length + array.length) * 2;
  5678. }
  5679. for (var index = 0; index < array.length; index++) {
  5680. this.data[this.length++] = (array.data || array)[index];
  5681. }
  5682. };
  5683. SmartArray.prototype.indexOf = function (value) {
  5684. var position = this.data.indexOf(value);
  5685. if (position >= this.length) {
  5686. return -1;
  5687. }
  5688. return position;
  5689. };
  5690. SmartArray.prototype.contains = function (value) {
  5691. return this.data.indexOf(value) !== -1;
  5692. };
  5693. // Statics
  5694. SmartArray._GlobalId = 0;
  5695. return SmartArray;
  5696. }());
  5697. BABYLON.SmartArray = SmartArray;
  5698. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  5699. __extends(SmartArrayNoDuplicate, _super);
  5700. function SmartArrayNoDuplicate() {
  5701. var _this = _super !== null && _super.apply(this, arguments) || this;
  5702. _this._duplicateId = 0;
  5703. return _this;
  5704. }
  5705. SmartArrayNoDuplicate.prototype.push = function (value) {
  5706. _super.prototype.push.call(this, value);
  5707. if (!value.__smartArrayFlags) {
  5708. value.__smartArrayFlags = {};
  5709. }
  5710. value.__smartArrayFlags[this._id] = this._duplicateId;
  5711. };
  5712. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  5713. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5714. return false;
  5715. }
  5716. this.push(value);
  5717. return true;
  5718. };
  5719. SmartArrayNoDuplicate.prototype.reset = function () {
  5720. _super.prototype.reset.call(this);
  5721. this._duplicateId++;
  5722. };
  5723. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  5724. if (array.length === 0) {
  5725. return;
  5726. }
  5727. if (this.length + array.length > this.data.length) {
  5728. this.data.length = (this.length + array.length) * 2;
  5729. }
  5730. for (var index = 0; index < array.length; index++) {
  5731. var item = (array.data || array)[index];
  5732. this.pushNoDuplicate(item);
  5733. }
  5734. };
  5735. return SmartArrayNoDuplicate;
  5736. }(SmartArray));
  5737. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  5738. })(BABYLON || (BABYLON = {}));
  5739. //# sourceMappingURL=babylon.smartArray.js.map
  5740. var BABYLON;
  5741. (function (BABYLON) {
  5742. // Screenshots
  5743. var screenshotCanvas;
  5744. var cloneValue = function (source, destinationObject) {
  5745. if (!source)
  5746. return null;
  5747. if (source instanceof BABYLON.Mesh) {
  5748. return null;
  5749. }
  5750. if (source instanceof BABYLON.SubMesh) {
  5751. return source.clone(destinationObject);
  5752. }
  5753. else if (source.clone) {
  5754. return source.clone();
  5755. }
  5756. return null;
  5757. };
  5758. var Tools = /** @class */ (function () {
  5759. function Tools() {
  5760. }
  5761. /**
  5762. * Interpolates between a and b via alpha
  5763. * @param a The lower value (returned when alpha = 0)
  5764. * @param b The upper value (returned when alpha = 1)
  5765. * @param alpha The interpolation-factor
  5766. * @return The mixed value
  5767. */
  5768. Tools.Mix = function (a, b, alpha) {
  5769. return a * (1 - alpha) + b * alpha;
  5770. };
  5771. Tools.Instantiate = function (className) {
  5772. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  5773. return Tools.RegisteredExternalClasses[className];
  5774. }
  5775. var arr = className.split(".");
  5776. var fn = (window || this);
  5777. for (var i = 0, len = arr.length; i < len; i++) {
  5778. fn = fn[arr[i]];
  5779. }
  5780. if (typeof fn !== "function") {
  5781. return null;
  5782. }
  5783. return fn;
  5784. };
  5785. Tools.SetImmediate = function (action) {
  5786. if (window.setImmediate) {
  5787. window.setImmediate(action);
  5788. }
  5789. else {
  5790. setTimeout(action, 1);
  5791. }
  5792. };
  5793. Tools.IsExponentOfTwo = function (value) {
  5794. var count = 1;
  5795. do {
  5796. count *= 2;
  5797. } while (count < value);
  5798. return count === value;
  5799. };
  5800. /**
  5801. * Find the next highest power of two.
  5802. * @param x Number to start search from.
  5803. * @return Next highest power of two.
  5804. */
  5805. Tools.CeilingPOT = function (x) {
  5806. x--;
  5807. x |= x >> 1;
  5808. x |= x >> 2;
  5809. x |= x >> 4;
  5810. x |= x >> 8;
  5811. x |= x >> 16;
  5812. x++;
  5813. return x;
  5814. };
  5815. /**
  5816. * Find the next lowest power of two.
  5817. * @param x Number to start search from.
  5818. * @return Next lowest power of two.
  5819. */
  5820. Tools.FloorPOT = function (x) {
  5821. x = x | (x >> 1);
  5822. x = x | (x >> 2);
  5823. x = x | (x >> 4);
  5824. x = x | (x >> 8);
  5825. x = x | (x >> 16);
  5826. return x - (x >> 1);
  5827. };
  5828. /**
  5829. * Find the nearest power of two.
  5830. * @param x Number to start search from.
  5831. * @return Next nearest power of two.
  5832. */
  5833. Tools.NearestPOT = function (x) {
  5834. var c = Tools.CeilingPOT(x);
  5835. var f = Tools.FloorPOT(x);
  5836. return (c - x) > (x - f) ? f : c;
  5837. };
  5838. Tools.GetExponentOfTwo = function (value, max, mode) {
  5839. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5840. var pot;
  5841. switch (mode) {
  5842. case BABYLON.Engine.SCALEMODE_FLOOR:
  5843. pot = Tools.FloorPOT(value);
  5844. break;
  5845. case BABYLON.Engine.SCALEMODE_NEAREST:
  5846. pot = Tools.NearestPOT(value);
  5847. break;
  5848. case BABYLON.Engine.SCALEMODE_CEILING:
  5849. default:
  5850. pot = Tools.CeilingPOT(value);
  5851. break;
  5852. }
  5853. return Math.min(pot, max);
  5854. };
  5855. Tools.GetFilename = function (path) {
  5856. var index = path.lastIndexOf("/");
  5857. if (index < 0)
  5858. return path;
  5859. return path.substring(index + 1);
  5860. };
  5861. Tools.GetFolderPath = function (uri) {
  5862. var index = uri.lastIndexOf("/");
  5863. if (index < 0)
  5864. return "";
  5865. return uri.substring(0, index + 1);
  5866. };
  5867. Tools.GetDOMTextContent = function (element) {
  5868. var result = "";
  5869. var child = element.firstChild;
  5870. while (child) {
  5871. if (child.nodeType === 3) {
  5872. result += child.textContent;
  5873. }
  5874. child = child.nextSibling;
  5875. }
  5876. return result;
  5877. };
  5878. Tools.ToDegrees = function (angle) {
  5879. return angle * 180 / Math.PI;
  5880. };
  5881. Tools.ToRadians = function (angle) {
  5882. return angle * Math.PI / 180;
  5883. };
  5884. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5885. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5886. var output = "";
  5887. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5888. var i = 0;
  5889. var bytes = new Uint8Array(buffer);
  5890. while (i < bytes.length) {
  5891. chr1 = bytes[i++];
  5892. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5893. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5894. enc1 = chr1 >> 2;
  5895. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5896. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5897. enc4 = chr3 & 63;
  5898. if (isNaN(chr2)) {
  5899. enc3 = enc4 = 64;
  5900. }
  5901. else if (isNaN(chr3)) {
  5902. enc4 = 64;
  5903. }
  5904. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5905. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5906. }
  5907. return "data:image/png;base64," + output;
  5908. };
  5909. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5910. if (bias === void 0) { bias = null; }
  5911. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5912. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5913. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5914. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5915. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5916. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5917. }
  5918. if (bias) {
  5919. minimum.x -= minimum.x * bias.x + bias.y;
  5920. minimum.y -= minimum.y * bias.x + bias.y;
  5921. minimum.z -= minimum.z * bias.x + bias.y;
  5922. maximum.x += maximum.x * bias.x + bias.y;
  5923. maximum.y += maximum.y * bias.x + bias.y;
  5924. maximum.z += maximum.z * bias.x + bias.y;
  5925. }
  5926. return {
  5927. minimum: minimum,
  5928. maximum: maximum
  5929. };
  5930. };
  5931. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5932. if (bias === void 0) { bias = null; }
  5933. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5934. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5935. if (!stride) {
  5936. stride = 3;
  5937. }
  5938. for (var index = start; index < start + count; index++) {
  5939. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5940. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5941. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5942. }
  5943. if (bias) {
  5944. minimum.x -= minimum.x * bias.x + bias.y;
  5945. minimum.y -= minimum.y * bias.x + bias.y;
  5946. minimum.z -= minimum.z * bias.x + bias.y;
  5947. maximum.x += maximum.x * bias.x + bias.y;
  5948. maximum.y += maximum.y * bias.x + bias.y;
  5949. maximum.z += maximum.z * bias.x + bias.y;
  5950. }
  5951. return {
  5952. minimum: minimum,
  5953. maximum: maximum
  5954. };
  5955. };
  5956. Tools.Vector2ArrayFeeder = function (array) {
  5957. return function (index) {
  5958. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5959. var length = isFloatArray ? array.length / 2 : array.length;
  5960. if (index >= length) {
  5961. return null;
  5962. }
  5963. if (isFloatArray) {
  5964. var fa = array;
  5965. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5966. }
  5967. var a = array;
  5968. return a[index];
  5969. };
  5970. };
  5971. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5972. if (bias === void 0) { bias = null; }
  5973. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5974. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5975. var i = 0;
  5976. var cur = feeder(i++);
  5977. while (cur) {
  5978. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5979. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5980. cur = feeder(i++);
  5981. }
  5982. if (bias) {
  5983. minimum.x -= minimum.x * bias.x + bias.y;
  5984. minimum.y -= minimum.y * bias.x + bias.y;
  5985. maximum.x += maximum.x * bias.x + bias.y;
  5986. maximum.y += maximum.y * bias.x + bias.y;
  5987. }
  5988. return {
  5989. minimum: minimum,
  5990. maximum: maximum
  5991. };
  5992. };
  5993. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5994. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5995. return null;
  5996. return Array.isArray(obj) ? obj : [obj];
  5997. };
  5998. // Misc.
  5999. Tools.GetPointerPrefix = function () {
  6000. var eventPrefix = "pointer";
  6001. // Check if pointer events are supported
  6002. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  6003. eventPrefix = "mouse";
  6004. }
  6005. return eventPrefix;
  6006. };
  6007. /**
  6008. * @param func - the function to be called
  6009. * @param requester - the object that will request the next frame. Falls back to window.
  6010. */
  6011. Tools.QueueNewFrame = function (func, requester) {
  6012. if (!Tools.IsWindowObjectExist()) {
  6013. return setTimeout(func, 16);
  6014. }
  6015. if (!requester) {
  6016. requester = window;
  6017. }
  6018. if (requester.requestAnimationFrame) {
  6019. return requester.requestAnimationFrame(func);
  6020. }
  6021. else if (requester.msRequestAnimationFrame) {
  6022. return requester.msRequestAnimationFrame(func);
  6023. }
  6024. else if (requester.webkitRequestAnimationFrame) {
  6025. return requester.webkitRequestAnimationFrame(func);
  6026. }
  6027. else if (requester.mozRequestAnimationFrame) {
  6028. return requester.mozRequestAnimationFrame(func);
  6029. }
  6030. else if (requester.oRequestAnimationFrame) {
  6031. return requester.oRequestAnimationFrame(func);
  6032. }
  6033. else {
  6034. return window.setTimeout(func, 16);
  6035. }
  6036. };
  6037. Tools.RequestFullscreen = function (element) {
  6038. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6039. if (!requestFunction)
  6040. return;
  6041. requestFunction.call(element);
  6042. };
  6043. Tools.ExitFullscreen = function () {
  6044. if (document.exitFullscreen) {
  6045. document.exitFullscreen();
  6046. }
  6047. else if (document.mozCancelFullScreen) {
  6048. document.mozCancelFullScreen();
  6049. }
  6050. else if (document.webkitCancelFullScreen) {
  6051. document.webkitCancelFullScreen();
  6052. }
  6053. else if (document.msCancelFullScreen) {
  6054. document.msCancelFullScreen();
  6055. }
  6056. };
  6057. Tools.SetCorsBehavior = function (url, img) {
  6058. if (Tools.CorsBehavior) {
  6059. switch (typeof (Tools.CorsBehavior)) {
  6060. case "function":
  6061. var result = Tools.CorsBehavior(url);
  6062. if (result) {
  6063. img.crossOrigin = result;
  6064. }
  6065. break;
  6066. case "string":
  6067. default:
  6068. img.crossOrigin = Tools.CorsBehavior;
  6069. break;
  6070. }
  6071. }
  6072. };
  6073. // External files
  6074. Tools.CleanUrl = function (url) {
  6075. url = url.replace(/#/mg, "%23");
  6076. return url;
  6077. };
  6078. Tools.LoadImage = function (url, onLoad, onError, database) {
  6079. if (url instanceof ArrayBuffer) {
  6080. url = Tools.EncodeArrayBufferTobase64(url);
  6081. }
  6082. url = Tools.CleanUrl(url);
  6083. url = Tools.PreprocessUrl(url);
  6084. var img = new Image();
  6085. if (url.substr(0, 5) !== "data:") {
  6086. Tools.SetCorsBehavior(url, img);
  6087. }
  6088. img.onload = function () {
  6089. onLoad(img);
  6090. };
  6091. img.onerror = function (err) {
  6092. Tools.Error("Error while trying to load image: " + url);
  6093. if (onError) {
  6094. onError("Error while trying to load image: " + url, err);
  6095. }
  6096. };
  6097. var noIndexedDB = function () {
  6098. img.src = url;
  6099. };
  6100. var loadFromIndexedDB = function () {
  6101. if (database) {
  6102. database.loadImageFromDB(url, img);
  6103. }
  6104. };
  6105. //ANY database to do!
  6106. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6107. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6108. }
  6109. else {
  6110. if (url.indexOf("file:") !== -1) {
  6111. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  6112. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  6113. try {
  6114. var blobURL;
  6115. try {
  6116. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  6117. }
  6118. catch (ex) {
  6119. // Chrome doesn't support oneTimeOnly parameter
  6120. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  6121. }
  6122. img.src = blobURL;
  6123. }
  6124. catch (e) {
  6125. img.src = "";
  6126. }
  6127. return img;
  6128. }
  6129. }
  6130. noIndexedDB();
  6131. }
  6132. return img;
  6133. };
  6134. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  6135. url = Tools.CleanUrl(url);
  6136. url = Tools.PreprocessUrl(url);
  6137. var request = null;
  6138. var noIndexedDB = function () {
  6139. request = new XMLHttpRequest();
  6140. var loadUrl = Tools.BaseUrl + url;
  6141. request.open('GET', loadUrl, true);
  6142. if (useArrayBuffer) {
  6143. request.responseType = "arraybuffer";
  6144. }
  6145. if (progressCallBack) {
  6146. request.onprogress = progressCallBack;
  6147. }
  6148. request.onreadystatechange = function () {
  6149. var req = request;
  6150. // In case of undefined state in some browsers.
  6151. if (req.readyState === (XMLHttpRequest.DONE || 4)) {
  6152. req.onreadystatechange = function () { }; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6153. if (req.status >= 200 && req.status < 300 || (!Tools.IsWindowObjectExist() && (req.status === 0))) {
  6154. callback(!useArrayBuffer ? req.responseText : req.response, req.responseURL);
  6155. }
  6156. else {
  6157. var e = new Error("Error status: " + req.status + " - Unable to load " + loadUrl);
  6158. if (onError) {
  6159. onError(req, e);
  6160. }
  6161. else {
  6162. throw e;
  6163. }
  6164. }
  6165. }
  6166. };
  6167. request.send(null);
  6168. };
  6169. var loadFromIndexedDB = function () {
  6170. if (database) {
  6171. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6172. }
  6173. };
  6174. // If file and file input are set
  6175. if (url.indexOf("file:") !== -1) {
  6176. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  6177. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6178. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6179. return request;
  6180. }
  6181. }
  6182. // Caching all files
  6183. if (database && database.enableSceneOffline) {
  6184. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6185. }
  6186. else {
  6187. noIndexedDB();
  6188. }
  6189. return request;
  6190. };
  6191. /**
  6192. * Load a script (identified by an url). When the url returns, the
  6193. * content of this file is added into a new script element, attached to the DOM (body element)
  6194. */
  6195. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6196. var head = document.getElementsByTagName('head')[0];
  6197. var script = document.createElement('script');
  6198. script.type = 'text/javascript';
  6199. script.src = scriptUrl;
  6200. script.onload = function () {
  6201. if (onSuccess) {
  6202. onSuccess();
  6203. }
  6204. };
  6205. script.onerror = function (e) {
  6206. if (onError) {
  6207. onError("Unable to load script", e);
  6208. }
  6209. };
  6210. head.appendChild(script);
  6211. };
  6212. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6213. var reader = new FileReader();
  6214. reader.onload = function (e) {
  6215. //target doesn't have result from ts 1.3
  6216. callback(e.target['result']);
  6217. };
  6218. reader.onprogress = progressCallback;
  6219. reader.readAsDataURL(fileToLoad);
  6220. };
  6221. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6222. var reader = new FileReader();
  6223. reader.onerror = function (e) {
  6224. Tools.Log("Error while reading file: " + fileToLoad.name);
  6225. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6226. };
  6227. reader.onload = function (e) {
  6228. //target doesn't have result from ts 1.3
  6229. callback(e.target['result']);
  6230. };
  6231. if (progressCallBack) {
  6232. reader.onprogress = progressCallBack;
  6233. }
  6234. if (!useArrayBuffer) {
  6235. // Asynchronous read
  6236. reader.readAsText(fileToLoad);
  6237. }
  6238. else {
  6239. reader.readAsArrayBuffer(fileToLoad);
  6240. }
  6241. };
  6242. //returns a downloadable url to a file content.
  6243. Tools.FileAsURL = function (content) {
  6244. var fileBlob = new Blob([content]);
  6245. var url = window.URL || window.webkitURL;
  6246. var link = url.createObjectURL(fileBlob);
  6247. return link;
  6248. };
  6249. // Misc.
  6250. Tools.Format = function (value, decimals) {
  6251. if (decimals === void 0) { decimals = 2; }
  6252. return value.toFixed(decimals);
  6253. };
  6254. Tools.CheckExtends = function (v, min, max) {
  6255. if (v.x < min.x)
  6256. min.x = v.x;
  6257. if (v.y < min.y)
  6258. min.y = v.y;
  6259. if (v.z < min.z)
  6260. min.z = v.z;
  6261. if (v.x > max.x)
  6262. max.x = v.x;
  6263. if (v.y > max.y)
  6264. max.y = v.y;
  6265. if (v.z > max.z)
  6266. max.z = v.z;
  6267. };
  6268. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6269. for (var prop in source) {
  6270. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6271. continue;
  6272. }
  6273. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6274. continue;
  6275. }
  6276. var sourceValue = source[prop];
  6277. var typeOfSourceValue = typeof sourceValue;
  6278. if (typeOfSourceValue === "function") {
  6279. continue;
  6280. }
  6281. if (typeOfSourceValue === "object") {
  6282. if (sourceValue instanceof Array) {
  6283. destination[prop] = [];
  6284. if (sourceValue.length > 0) {
  6285. if (typeof sourceValue[0] == "object") {
  6286. for (var index = 0; index < sourceValue.length; index++) {
  6287. var clonedValue = cloneValue(sourceValue[index], destination);
  6288. if (destination[prop].indexOf(clonedValue) === -1) {
  6289. destination[prop].push(clonedValue);
  6290. }
  6291. }
  6292. }
  6293. else {
  6294. destination[prop] = sourceValue.slice(0);
  6295. }
  6296. }
  6297. }
  6298. else {
  6299. destination[prop] = cloneValue(sourceValue, destination);
  6300. }
  6301. }
  6302. else {
  6303. destination[prop] = sourceValue;
  6304. }
  6305. }
  6306. };
  6307. Tools.IsEmpty = function (obj) {
  6308. for (var i in obj) {
  6309. if (obj.hasOwnProperty(i)) {
  6310. return false;
  6311. }
  6312. }
  6313. return true;
  6314. };
  6315. Tools.RegisterTopRootEvents = function (events) {
  6316. for (var index = 0; index < events.length; index++) {
  6317. var event = events[index];
  6318. window.addEventListener(event.name, event.handler, false);
  6319. try {
  6320. if (window.parent) {
  6321. window.parent.addEventListener(event.name, event.handler, false);
  6322. }
  6323. }
  6324. catch (e) {
  6325. // Silently fails...
  6326. }
  6327. }
  6328. };
  6329. Tools.UnregisterTopRootEvents = function (events) {
  6330. for (var index = 0; index < events.length; index++) {
  6331. var event = events[index];
  6332. window.removeEventListener(event.name, event.handler);
  6333. try {
  6334. if (window.parent) {
  6335. window.parent.removeEventListener(event.name, event.handler);
  6336. }
  6337. }
  6338. catch (e) {
  6339. // Silently fails...
  6340. }
  6341. }
  6342. };
  6343. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  6344. if (mimeType === void 0) { mimeType = "image/png"; }
  6345. // Read the contents of the framebuffer
  6346. var numberOfChannelsByLine = width * 4;
  6347. var halfHeight = height / 2;
  6348. //Reading datas from WebGL
  6349. var data = engine.readPixels(0, 0, width, height);
  6350. //To flip image on Y axis.
  6351. for (var i = 0; i < halfHeight; i++) {
  6352. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6353. var currentCell = j + i * numberOfChannelsByLine;
  6354. var targetLine = height - i - 1;
  6355. var targetCell = j + targetLine * numberOfChannelsByLine;
  6356. var temp = data[currentCell];
  6357. data[currentCell] = data[targetCell];
  6358. data[targetCell] = temp;
  6359. }
  6360. }
  6361. // Create a 2D canvas to store the result
  6362. if (!screenshotCanvas) {
  6363. screenshotCanvas = document.createElement('canvas');
  6364. }
  6365. screenshotCanvas.width = width;
  6366. screenshotCanvas.height = height;
  6367. var context = screenshotCanvas.getContext('2d');
  6368. if (context) {
  6369. // Copy the pixels to a 2D canvas
  6370. var imageData = context.createImageData(width, height);
  6371. var castData = (imageData.data);
  6372. castData.set(data);
  6373. context.putImageData(imageData, 0, 0);
  6374. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  6375. }
  6376. };
  6377. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  6378. if (mimeType === void 0) { mimeType = "image/png"; }
  6379. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6380. if (successCallback) {
  6381. successCallback(base64Image);
  6382. }
  6383. else {
  6384. // We need HTMLCanvasElement.toBlob for HD screenshots
  6385. if (!screenshotCanvas.toBlob) {
  6386. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  6387. screenshotCanvas.toBlob = function (callback, type, quality) {
  6388. var _this = this;
  6389. setTimeout(function () {
  6390. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  6391. for (var i = 0; i < len; i++) {
  6392. arr[i] = binStr.charCodeAt(i);
  6393. }
  6394. callback(new Blob([arr], { type: type || 'image/png' }));
  6395. });
  6396. };
  6397. }
  6398. screenshotCanvas.toBlob(function (blob) {
  6399. var url = URL.createObjectURL(blob);
  6400. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6401. if (("download" in document.createElement("a"))) {
  6402. var a = window.document.createElement("a");
  6403. a.href = url;
  6404. if (fileName) {
  6405. a.setAttribute("download", fileName);
  6406. }
  6407. else {
  6408. var date = new Date();
  6409. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6410. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6411. }
  6412. window.document.body.appendChild(a);
  6413. a.addEventListener("click", function () {
  6414. if (a.parentElement) {
  6415. a.parentElement.removeChild(a);
  6416. }
  6417. });
  6418. a.click();
  6419. }
  6420. else {
  6421. var newWindow = window.open("");
  6422. if (!newWindow)
  6423. return;
  6424. var img = newWindow.document.createElement("img");
  6425. img.onload = function () {
  6426. // no longer need to read the blob so it's revoked
  6427. URL.revokeObjectURL(url);
  6428. };
  6429. img.src = url;
  6430. newWindow.document.body.appendChild(img);
  6431. }
  6432. });
  6433. }
  6434. };
  6435. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6436. if (mimeType === void 0) { mimeType = "image/png"; }
  6437. var width;
  6438. var height;
  6439. // If a precision value is specified
  6440. if (size.precision) {
  6441. width = Math.round(engine.getRenderWidth() * size.precision);
  6442. height = Math.round(width / engine.getAspectRatio(camera));
  6443. }
  6444. else if (size.width && size.height) {
  6445. width = size.width;
  6446. height = size.height;
  6447. }
  6448. else if (size.width && !size.height) {
  6449. width = size.width;
  6450. height = Math.round(width / engine.getAspectRatio(camera));
  6451. }
  6452. else if (size.height && !size.width) {
  6453. height = size.height;
  6454. width = Math.round(height * engine.getAspectRatio(camera));
  6455. }
  6456. else if (!isNaN(size)) {
  6457. height = size;
  6458. width = size;
  6459. }
  6460. else {
  6461. Tools.Error("Invalid 'size' parameter !");
  6462. return;
  6463. }
  6464. if (!screenshotCanvas) {
  6465. screenshotCanvas = document.createElement('canvas');
  6466. }
  6467. screenshotCanvas.width = width;
  6468. screenshotCanvas.height = height;
  6469. var renderContext = screenshotCanvas.getContext("2d");
  6470. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6471. var newWidth = width;
  6472. var newHeight = newWidth / ratio;
  6473. if (newHeight > height) {
  6474. newHeight = height;
  6475. newWidth = newHeight * ratio;
  6476. }
  6477. var offsetX = Math.max(0, width - newWidth) / 2;
  6478. var offsetY = Math.max(0, height - newHeight) / 2;
  6479. var renderingCanvas = engine.getRenderingCanvas();
  6480. if (renderContext && renderingCanvas) {
  6481. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  6482. }
  6483. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6484. };
  6485. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  6486. if (mimeType === void 0) { mimeType = "image/png"; }
  6487. if (samples === void 0) { samples = 1; }
  6488. if (antialiasing === void 0) { antialiasing = false; }
  6489. var width;
  6490. var height;
  6491. //If a precision value is specified
  6492. if (size.precision) {
  6493. width = Math.round(engine.getRenderWidth() * size.precision);
  6494. height = Math.round(width / engine.getAspectRatio(camera));
  6495. size = { width: width, height: height };
  6496. }
  6497. else if (size.width && size.height) {
  6498. width = size.width;
  6499. height = size.height;
  6500. }
  6501. else if (size.width && !size.height) {
  6502. width = size.width;
  6503. height = Math.round(width / engine.getAspectRatio(camera));
  6504. size = { width: width, height: height };
  6505. }
  6506. else if (size.height && !size.width) {
  6507. height = size.height;
  6508. width = Math.round(height * engine.getAspectRatio(camera));
  6509. size = { width: width, height: height };
  6510. }
  6511. else if (!isNaN(size)) {
  6512. height = size;
  6513. width = size;
  6514. }
  6515. else {
  6516. Tools.Error("Invalid 'size' parameter !");
  6517. return;
  6518. }
  6519. var scene = camera.getScene();
  6520. var previousCamera = null;
  6521. if (scene.activeCamera !== camera) {
  6522. previousCamera = scene.activeCamera;
  6523. scene.activeCamera = camera;
  6524. }
  6525. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6526. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6527. texture.renderList = null;
  6528. texture.samples = samples;
  6529. if (antialiasing) {
  6530. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  6531. }
  6532. texture.onAfterRenderObservable.add(function () {
  6533. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  6534. });
  6535. scene.incrementRenderId();
  6536. scene.resetCachedMaterial();
  6537. texture.render(true);
  6538. texture.dispose();
  6539. if (previousCamera) {
  6540. scene.activeCamera = previousCamera;
  6541. }
  6542. camera.getProjectionMatrix(true); // Force cache refresh;
  6543. };
  6544. // XHR response validator for local file scenario
  6545. Tools.ValidateXHRData = function (xhr, dataType) {
  6546. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6547. if (dataType === void 0) { dataType = 7; }
  6548. try {
  6549. if (dataType & 1) {
  6550. if (xhr.responseText && xhr.responseText.length > 0) {
  6551. return true;
  6552. }
  6553. else if (dataType === 1) {
  6554. return false;
  6555. }
  6556. }
  6557. if (dataType & 2) {
  6558. // Check header width and height since there is no "TGA" magic number
  6559. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6560. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6561. return true;
  6562. }
  6563. else if (dataType === 2) {
  6564. return false;
  6565. }
  6566. }
  6567. if (dataType & 4) {
  6568. // Check for the "DDS" magic number
  6569. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6570. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6571. return true;
  6572. }
  6573. else {
  6574. return false;
  6575. }
  6576. }
  6577. }
  6578. catch (e) {
  6579. // Global protection
  6580. }
  6581. return false;
  6582. };
  6583. /**
  6584. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6585. * Be aware Math.random() could cause collisions, but:
  6586. * "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"
  6587. */
  6588. Tools.RandomId = function () {
  6589. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6590. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6591. return v.toString(16);
  6592. });
  6593. };
  6594. Object.defineProperty(Tools, "NoneLogLevel", {
  6595. get: function () {
  6596. return Tools._NoneLogLevel;
  6597. },
  6598. enumerable: true,
  6599. configurable: true
  6600. });
  6601. Object.defineProperty(Tools, "MessageLogLevel", {
  6602. get: function () {
  6603. return Tools._MessageLogLevel;
  6604. },
  6605. enumerable: true,
  6606. configurable: true
  6607. });
  6608. Object.defineProperty(Tools, "WarningLogLevel", {
  6609. get: function () {
  6610. return Tools._WarningLogLevel;
  6611. },
  6612. enumerable: true,
  6613. configurable: true
  6614. });
  6615. Object.defineProperty(Tools, "ErrorLogLevel", {
  6616. get: function () {
  6617. return Tools._ErrorLogLevel;
  6618. },
  6619. enumerable: true,
  6620. configurable: true
  6621. });
  6622. Object.defineProperty(Tools, "AllLogLevel", {
  6623. get: function () {
  6624. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6625. },
  6626. enumerable: true,
  6627. configurable: true
  6628. });
  6629. Tools._AddLogEntry = function (entry) {
  6630. Tools._LogCache = entry + Tools._LogCache;
  6631. if (Tools.OnNewCacheEntry) {
  6632. Tools.OnNewCacheEntry(entry);
  6633. }
  6634. };
  6635. Tools._FormatMessage = function (message) {
  6636. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6637. var date = new Date();
  6638. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6639. };
  6640. Tools._LogDisabled = function (message) {
  6641. // nothing to do
  6642. };
  6643. Tools._LogEnabled = function (message) {
  6644. var formattedMessage = Tools._FormatMessage(message);
  6645. console.log("BJS - " + formattedMessage);
  6646. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6647. Tools._AddLogEntry(entry);
  6648. };
  6649. Tools._WarnDisabled = function (message) {
  6650. // nothing to do
  6651. };
  6652. Tools._WarnEnabled = function (message) {
  6653. var formattedMessage = Tools._FormatMessage(message);
  6654. console.warn("BJS - " + formattedMessage);
  6655. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6656. Tools._AddLogEntry(entry);
  6657. };
  6658. Tools._ErrorDisabled = function (message) {
  6659. // nothing to do
  6660. };
  6661. Tools._ErrorEnabled = function (message) {
  6662. Tools.errorsCount++;
  6663. var formattedMessage = Tools._FormatMessage(message);
  6664. console.error("BJS - " + formattedMessage);
  6665. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6666. Tools._AddLogEntry(entry);
  6667. };
  6668. Object.defineProperty(Tools, "LogCache", {
  6669. get: function () {
  6670. return Tools._LogCache;
  6671. },
  6672. enumerable: true,
  6673. configurable: true
  6674. });
  6675. Tools.ClearLogCache = function () {
  6676. Tools._LogCache = "";
  6677. Tools.errorsCount = 0;
  6678. };
  6679. Object.defineProperty(Tools, "LogLevels", {
  6680. set: function (level) {
  6681. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6682. Tools.Log = Tools._LogEnabled;
  6683. }
  6684. else {
  6685. Tools.Log = Tools._LogDisabled;
  6686. }
  6687. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6688. Tools.Warn = Tools._WarnEnabled;
  6689. }
  6690. else {
  6691. Tools.Warn = Tools._WarnDisabled;
  6692. }
  6693. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6694. Tools.Error = Tools._ErrorEnabled;
  6695. }
  6696. else {
  6697. Tools.Error = Tools._ErrorDisabled;
  6698. }
  6699. },
  6700. enumerable: true,
  6701. configurable: true
  6702. });
  6703. Tools.IsWindowObjectExist = function () {
  6704. return (typeof window) !== "undefined";
  6705. };
  6706. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6707. get: function () {
  6708. return Tools._PerformanceNoneLogLevel;
  6709. },
  6710. enumerable: true,
  6711. configurable: true
  6712. });
  6713. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6714. get: function () {
  6715. return Tools._PerformanceUserMarkLogLevel;
  6716. },
  6717. enumerable: true,
  6718. configurable: true
  6719. });
  6720. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6721. get: function () {
  6722. return Tools._PerformanceConsoleLogLevel;
  6723. },
  6724. enumerable: true,
  6725. configurable: true
  6726. });
  6727. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6728. set: function (level) {
  6729. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6730. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6731. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6732. return;
  6733. }
  6734. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6735. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6736. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6737. return;
  6738. }
  6739. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6740. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6741. },
  6742. enumerable: true,
  6743. configurable: true
  6744. });
  6745. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6746. };
  6747. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6748. };
  6749. Tools._StartUserMark = function (counterName, condition) {
  6750. if (condition === void 0) { condition = true; }
  6751. if (!Tools._performance) {
  6752. if (!Tools.IsWindowObjectExist()) {
  6753. return;
  6754. }
  6755. Tools._performance = window.performance;
  6756. }
  6757. if (!condition || !Tools._performance.mark) {
  6758. return;
  6759. }
  6760. Tools._performance.mark(counterName + "-Begin");
  6761. };
  6762. Tools._EndUserMark = function (counterName, condition) {
  6763. if (condition === void 0) { condition = true; }
  6764. if (!condition || !Tools._performance.mark) {
  6765. return;
  6766. }
  6767. Tools._performance.mark(counterName + "-End");
  6768. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6769. };
  6770. Tools._StartPerformanceConsole = function (counterName, condition) {
  6771. if (condition === void 0) { condition = true; }
  6772. if (!condition) {
  6773. return;
  6774. }
  6775. Tools._StartUserMark(counterName, condition);
  6776. if (console.time) {
  6777. console.time(counterName);
  6778. }
  6779. };
  6780. Tools._EndPerformanceConsole = function (counterName, condition) {
  6781. if (condition === void 0) { condition = true; }
  6782. if (!condition) {
  6783. return;
  6784. }
  6785. Tools._EndUserMark(counterName, condition);
  6786. if (console.time) {
  6787. console.timeEnd(counterName);
  6788. }
  6789. };
  6790. Object.defineProperty(Tools, "Now", {
  6791. get: function () {
  6792. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  6793. return window.performance.now();
  6794. }
  6795. return new Date().getTime();
  6796. },
  6797. enumerable: true,
  6798. configurable: true
  6799. });
  6800. /**
  6801. * This method will return the name of the class used to create the instance of the given object.
  6802. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6803. * @param object the object to get the class name from
  6804. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6805. */
  6806. Tools.GetClassName = function (object, isType) {
  6807. if (isType === void 0) { isType = false; }
  6808. var name = null;
  6809. if (!isType && object.getClassName) {
  6810. name = object.getClassName();
  6811. }
  6812. else {
  6813. if (object instanceof Object) {
  6814. var classObj = isType ? object : Object.getPrototypeOf(object);
  6815. name = classObj.constructor["__bjsclassName__"];
  6816. }
  6817. if (!name) {
  6818. name = typeof object;
  6819. }
  6820. }
  6821. return name;
  6822. };
  6823. Tools.First = function (array, predicate) {
  6824. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6825. var el = array_1[_i];
  6826. if (predicate(el)) {
  6827. return el;
  6828. }
  6829. }
  6830. return null;
  6831. };
  6832. /**
  6833. * This method will return the name of the full name of the class, including its owning module (if any).
  6834. * 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).
  6835. * @param object the object to get the class name from
  6836. * @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.
  6837. */
  6838. Tools.getFullClassName = function (object, isType) {
  6839. if (isType === void 0) { isType = false; }
  6840. var className = null;
  6841. var moduleName = null;
  6842. if (!isType && object.getClassName) {
  6843. className = object.getClassName();
  6844. }
  6845. else {
  6846. if (object instanceof Object) {
  6847. var classObj = isType ? object : Object.getPrototypeOf(object);
  6848. className = classObj.constructor["__bjsclassName__"];
  6849. moduleName = classObj.constructor["__bjsmoduleName__"];
  6850. }
  6851. if (!className) {
  6852. className = typeof object;
  6853. }
  6854. }
  6855. if (!className) {
  6856. return null;
  6857. }
  6858. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6859. };
  6860. /**
  6861. * 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.
  6862. * @param array
  6863. */
  6864. Tools.arrayOrStringFeeder = function (array) {
  6865. return function (index) {
  6866. if (index >= array.length) {
  6867. return null;
  6868. }
  6869. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6870. if (val && val.getHashCode) {
  6871. val = val.getHashCode();
  6872. }
  6873. if (typeof val === "string") {
  6874. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6875. }
  6876. return val;
  6877. };
  6878. };
  6879. /**
  6880. * Compute the hashCode of a stream of number
  6881. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6882. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6883. * @return the hash code computed
  6884. */
  6885. Tools.hashCodeFromStream = function (feeder) {
  6886. // Based from here: http://stackoverflow.com/a/7616484/802124
  6887. var hash = 0;
  6888. var index = 0;
  6889. var chr = feeder(index++);
  6890. while (chr != null) {
  6891. hash = ((hash << 5) - hash) + chr;
  6892. hash |= 0; // Convert to 32bit integer
  6893. chr = feeder(index++);
  6894. }
  6895. return hash;
  6896. };
  6897. Tools.BaseUrl = "";
  6898. Tools.CorsBehavior = "anonymous";
  6899. Tools.UseFallbackTexture = true;
  6900. /**
  6901. * Use this object to register external classes like custom textures or material
  6902. * to allow the laoders to instantiate them
  6903. */
  6904. Tools.RegisteredExternalClasses = {};
  6905. // Used in case of a texture loading problem
  6906. 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";
  6907. Tools.PreprocessUrl = function (url) {
  6908. return url;
  6909. };
  6910. // Logs
  6911. Tools._NoneLogLevel = 0;
  6912. Tools._MessageLogLevel = 1;
  6913. Tools._WarningLogLevel = 2;
  6914. Tools._ErrorLogLevel = 4;
  6915. Tools._LogCache = "";
  6916. Tools.errorsCount = 0;
  6917. Tools.Log = Tools._LogEnabled;
  6918. Tools.Warn = Tools._WarnEnabled;
  6919. Tools.Error = Tools._ErrorEnabled;
  6920. // Performances
  6921. Tools._PerformanceNoneLogLevel = 0;
  6922. Tools._PerformanceUserMarkLogLevel = 1;
  6923. Tools._PerformanceConsoleLogLevel = 2;
  6924. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6925. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6926. return Tools;
  6927. }());
  6928. BABYLON.Tools = Tools;
  6929. /**
  6930. * This class is used to track a performance counter which is number based.
  6931. * The user has access to many properties which give statistics of different nature
  6932. *
  6933. * The implementer can track two kinds of Performance Counter: time and count
  6934. * 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.
  6935. * 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.
  6936. */
  6937. var PerfCounter = /** @class */ (function () {
  6938. function PerfCounter() {
  6939. this._startMonitoringTime = 0;
  6940. this._min = 0;
  6941. this._max = 0;
  6942. this._average = 0;
  6943. this._lastSecAverage = 0;
  6944. this._current = 0;
  6945. this._totalValueCount = 0;
  6946. this._totalAccumulated = 0;
  6947. this._lastSecAccumulated = 0;
  6948. this._lastSecTime = 0;
  6949. this._lastSecValueCount = 0;
  6950. }
  6951. Object.defineProperty(PerfCounter.prototype, "min", {
  6952. /**
  6953. * Returns the smallest value ever
  6954. */
  6955. get: function () {
  6956. return this._min;
  6957. },
  6958. enumerable: true,
  6959. configurable: true
  6960. });
  6961. Object.defineProperty(PerfCounter.prototype, "max", {
  6962. /**
  6963. * Returns the biggest value ever
  6964. */
  6965. get: function () {
  6966. return this._max;
  6967. },
  6968. enumerable: true,
  6969. configurable: true
  6970. });
  6971. Object.defineProperty(PerfCounter.prototype, "average", {
  6972. /**
  6973. * Returns the average value since the performance counter is running
  6974. */
  6975. get: function () {
  6976. return this._average;
  6977. },
  6978. enumerable: true,
  6979. configurable: true
  6980. });
  6981. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6982. /**
  6983. * Returns the average value of the last second the counter was monitored
  6984. */
  6985. get: function () {
  6986. return this._lastSecAverage;
  6987. },
  6988. enumerable: true,
  6989. configurable: true
  6990. });
  6991. Object.defineProperty(PerfCounter.prototype, "current", {
  6992. /**
  6993. * Returns the current value
  6994. */
  6995. get: function () {
  6996. return this._current;
  6997. },
  6998. enumerable: true,
  6999. configurable: true
  7000. });
  7001. Object.defineProperty(PerfCounter.prototype, "total", {
  7002. get: function () {
  7003. return this._totalAccumulated;
  7004. },
  7005. enumerable: true,
  7006. configurable: true
  7007. });
  7008. Object.defineProperty(PerfCounter.prototype, "count", {
  7009. get: function () {
  7010. return this._totalValueCount;
  7011. },
  7012. enumerable: true,
  7013. configurable: true
  7014. });
  7015. /**
  7016. * Call this method to start monitoring a new frame.
  7017. * 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.
  7018. */
  7019. PerfCounter.prototype.fetchNewFrame = function () {
  7020. this._totalValueCount++;
  7021. this._current = 0;
  7022. this._lastSecValueCount++;
  7023. };
  7024. /**
  7025. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  7026. * @param newCount the count value to add to the monitored count
  7027. * @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.
  7028. */
  7029. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  7030. if (!PerfCounter.Enabled) {
  7031. return;
  7032. }
  7033. this._current += newCount;
  7034. if (fetchResult) {
  7035. this._fetchResult();
  7036. }
  7037. };
  7038. /**
  7039. * Start monitoring this performance counter
  7040. */
  7041. PerfCounter.prototype.beginMonitoring = function () {
  7042. if (!PerfCounter.Enabled) {
  7043. return;
  7044. }
  7045. this._startMonitoringTime = Tools.Now;
  7046. };
  7047. /**
  7048. * Compute the time lapsed since the previous beginMonitoring() call.
  7049. * @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
  7050. */
  7051. PerfCounter.prototype.endMonitoring = function (newFrame) {
  7052. if (newFrame === void 0) { newFrame = true; }
  7053. if (!PerfCounter.Enabled) {
  7054. return;
  7055. }
  7056. if (newFrame) {
  7057. this.fetchNewFrame();
  7058. }
  7059. var currentTime = Tools.Now;
  7060. this._current = currentTime - this._startMonitoringTime;
  7061. if (newFrame) {
  7062. this._fetchResult();
  7063. }
  7064. };
  7065. PerfCounter.prototype._fetchResult = function () {
  7066. this._totalAccumulated += this._current;
  7067. this._lastSecAccumulated += this._current;
  7068. // Min/Max update
  7069. this._min = Math.min(this._min, this._current);
  7070. this._max = Math.max(this._max, this._current);
  7071. this._average = this._totalAccumulated / this._totalValueCount;
  7072. // Reset last sec?
  7073. var now = Tools.Now;
  7074. if ((now - this._lastSecTime) > 1000) {
  7075. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7076. this._lastSecTime = now;
  7077. this._lastSecAccumulated = 0;
  7078. this._lastSecValueCount = 0;
  7079. }
  7080. };
  7081. PerfCounter.Enabled = true;
  7082. return PerfCounter;
  7083. }());
  7084. BABYLON.PerfCounter = PerfCounter;
  7085. /**
  7086. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7087. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7088. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7089. * @param name The name of the class, case should be preserved
  7090. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7091. */
  7092. function className(name, module) {
  7093. return function (target) {
  7094. target["__bjsclassName__"] = name;
  7095. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7096. };
  7097. }
  7098. BABYLON.className = className;
  7099. /**
  7100. * An implementation of a loop for asynchronous functions.
  7101. */
  7102. var AsyncLoop = /** @class */ (function () {
  7103. /**
  7104. * Constroctor.
  7105. * @param iterations the number of iterations.
  7106. * @param _fn the function to run each iteration
  7107. * @param _successCallback the callback that will be called upon succesful execution
  7108. * @param offset starting offset.
  7109. */
  7110. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7111. if (offset === void 0) { offset = 0; }
  7112. this.iterations = iterations;
  7113. this._fn = _fn;
  7114. this._successCallback = _successCallback;
  7115. this.index = offset - 1;
  7116. this._done = false;
  7117. }
  7118. /**
  7119. * Execute the next iteration. Must be called after the last iteration was finished.
  7120. */
  7121. AsyncLoop.prototype.executeNext = function () {
  7122. if (!this._done) {
  7123. if (this.index + 1 < this.iterations) {
  7124. ++this.index;
  7125. this._fn(this);
  7126. }
  7127. else {
  7128. this.breakLoop();
  7129. }
  7130. }
  7131. };
  7132. /**
  7133. * Break the loop and run the success callback.
  7134. */
  7135. AsyncLoop.prototype.breakLoop = function () {
  7136. this._done = true;
  7137. this._successCallback();
  7138. };
  7139. /**
  7140. * Helper function
  7141. */
  7142. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7143. if (offset === void 0) { offset = 0; }
  7144. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7145. loop.executeNext();
  7146. return loop;
  7147. };
  7148. /**
  7149. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7150. * @param iterations total number of iterations
  7151. * @param syncedIterations number of synchronous iterations in each async iteration.
  7152. * @param fn the function to call each iteration.
  7153. * @param callback a success call back that will be called when iterating stops.
  7154. * @param breakFunction a break condition (optional)
  7155. * @param timeout timeout settings for the setTimeout function. default - 0.
  7156. * @constructor
  7157. */
  7158. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7159. if (timeout === void 0) { timeout = 0; }
  7160. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7161. if (breakFunction && breakFunction())
  7162. loop.breakLoop();
  7163. else {
  7164. setTimeout(function () {
  7165. for (var i = 0; i < syncedIterations; ++i) {
  7166. var iteration = (loop.index * syncedIterations) + i;
  7167. if (iteration >= iterations)
  7168. break;
  7169. fn(iteration);
  7170. if (breakFunction && breakFunction()) {
  7171. loop.breakLoop();
  7172. break;
  7173. }
  7174. }
  7175. loop.executeNext();
  7176. }, timeout);
  7177. }
  7178. }, callback);
  7179. };
  7180. return AsyncLoop;
  7181. }());
  7182. BABYLON.AsyncLoop = AsyncLoop;
  7183. })(BABYLON || (BABYLON = {}));
  7184. //# sourceMappingURL=babylon.tools.js.map
  7185. var BABYLON;
  7186. (function (BABYLON) {
  7187. var Internals;
  7188. (function (Internals) {
  7189. var _AlphaState = /** @class */ (function () {
  7190. /**
  7191. * Initializes the state.
  7192. */
  7193. function _AlphaState() {
  7194. this._isAlphaBlendDirty = false;
  7195. this._isBlendFunctionParametersDirty = false;
  7196. this._isBlendEquationParametersDirty = false;
  7197. this._isBlendConstantsDirty = false;
  7198. this._alphaBlend = false;
  7199. this._blendFunctionParameters = new Array(4);
  7200. this._blendEquationParameters = new Array(2);
  7201. this._blendConstants = new Array(4);
  7202. this.reset();
  7203. }
  7204. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7205. get: function () {
  7206. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7207. },
  7208. enumerable: true,
  7209. configurable: true
  7210. });
  7211. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7212. get: function () {
  7213. return this._alphaBlend;
  7214. },
  7215. set: function (value) {
  7216. if (this._alphaBlend === value) {
  7217. return;
  7218. }
  7219. this._alphaBlend = value;
  7220. this._isAlphaBlendDirty = true;
  7221. },
  7222. enumerable: true,
  7223. configurable: true
  7224. });
  7225. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  7226. if (this._blendConstants[0] === r &&
  7227. this._blendConstants[1] === g &&
  7228. this._blendConstants[2] === b &&
  7229. this._blendConstants[3] === a) {
  7230. return;
  7231. }
  7232. this._blendConstants[0] = r;
  7233. this._blendConstants[1] = g;
  7234. this._blendConstants[2] = b;
  7235. this._blendConstants[3] = a;
  7236. this._isBlendConstantsDirty = true;
  7237. };
  7238. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7239. if (this._blendFunctionParameters[0] === value0 &&
  7240. this._blendFunctionParameters[1] === value1 &&
  7241. this._blendFunctionParameters[2] === value2 &&
  7242. this._blendFunctionParameters[3] === value3) {
  7243. return;
  7244. }
  7245. this._blendFunctionParameters[0] = value0;
  7246. this._blendFunctionParameters[1] = value1;
  7247. this._blendFunctionParameters[2] = value2;
  7248. this._blendFunctionParameters[3] = value3;
  7249. this._isBlendFunctionParametersDirty = true;
  7250. };
  7251. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  7252. if (this._blendEquationParameters[0] === rgb &&
  7253. this._blendEquationParameters[1] === alpha) {
  7254. return;
  7255. }
  7256. this._blendEquationParameters[0] = rgb;
  7257. this._blendEquationParameters[1] = alpha;
  7258. this._isBlendEquationParametersDirty = true;
  7259. };
  7260. _AlphaState.prototype.reset = function () {
  7261. this._alphaBlend = false;
  7262. this._blendFunctionParameters[0] = null;
  7263. this._blendFunctionParameters[1] = null;
  7264. this._blendFunctionParameters[2] = null;
  7265. this._blendFunctionParameters[3] = null;
  7266. this._blendEquationParameters[0] = null;
  7267. this._blendEquationParameters[1] = null;
  7268. this._blendConstants[0] = null;
  7269. this._blendConstants[1] = null;
  7270. this._blendConstants[2] = null;
  7271. this._blendConstants[3] = null;
  7272. this._isAlphaBlendDirty = true;
  7273. this._isBlendFunctionParametersDirty = false;
  7274. this._isBlendEquationParametersDirty = false;
  7275. this._isBlendConstantsDirty = false;
  7276. };
  7277. _AlphaState.prototype.apply = function (gl) {
  7278. if (!this.isDirty) {
  7279. return;
  7280. }
  7281. // Alpha blend
  7282. if (this._isAlphaBlendDirty) {
  7283. if (this._alphaBlend) {
  7284. gl.enable(gl.BLEND);
  7285. }
  7286. else {
  7287. gl.disable(gl.BLEND);
  7288. }
  7289. this._isAlphaBlendDirty = false;
  7290. }
  7291. // Alpha function
  7292. if (this._isBlendFunctionParametersDirty) {
  7293. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7294. this._isBlendFunctionParametersDirty = false;
  7295. }
  7296. // Alpha equation
  7297. if (this._isBlendEquationParametersDirty) {
  7298. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7299. this._isBlendEquationParametersDirty = false;
  7300. }
  7301. // Constants
  7302. if (this._isBlendConstantsDirty) {
  7303. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7304. this._isBlendConstantsDirty = false;
  7305. }
  7306. };
  7307. return _AlphaState;
  7308. }());
  7309. Internals._AlphaState = _AlphaState;
  7310. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7311. })(BABYLON || (BABYLON = {}));
  7312. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7313. var BABYLON;
  7314. (function (BABYLON) {
  7315. var Internals;
  7316. (function (Internals) {
  7317. var _DepthCullingState = /** @class */ (function () {
  7318. /**
  7319. * Initializes the state.
  7320. */
  7321. function _DepthCullingState() {
  7322. this._isDepthTestDirty = false;
  7323. this._isDepthMaskDirty = false;
  7324. this._isDepthFuncDirty = false;
  7325. this._isCullFaceDirty = false;
  7326. this._isCullDirty = false;
  7327. this._isZOffsetDirty = false;
  7328. this.reset();
  7329. }
  7330. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7331. get: function () {
  7332. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7333. },
  7334. enumerable: true,
  7335. configurable: true
  7336. });
  7337. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7338. get: function () {
  7339. return this._zOffset;
  7340. },
  7341. set: function (value) {
  7342. if (this._zOffset === value) {
  7343. return;
  7344. }
  7345. this._zOffset = value;
  7346. this._isZOffsetDirty = true;
  7347. },
  7348. enumerable: true,
  7349. configurable: true
  7350. });
  7351. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7352. get: function () {
  7353. return this._cullFace;
  7354. },
  7355. set: function (value) {
  7356. if (this._cullFace === value) {
  7357. return;
  7358. }
  7359. this._cullFace = value;
  7360. this._isCullFaceDirty = true;
  7361. },
  7362. enumerable: true,
  7363. configurable: true
  7364. });
  7365. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7366. get: function () {
  7367. return this._cull;
  7368. },
  7369. set: function (value) {
  7370. if (this._cull === value) {
  7371. return;
  7372. }
  7373. this._cull = value;
  7374. this._isCullDirty = true;
  7375. },
  7376. enumerable: true,
  7377. configurable: true
  7378. });
  7379. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7380. get: function () {
  7381. return this._depthFunc;
  7382. },
  7383. set: function (value) {
  7384. if (this._depthFunc === value) {
  7385. return;
  7386. }
  7387. this._depthFunc = value;
  7388. this._isDepthFuncDirty = true;
  7389. },
  7390. enumerable: true,
  7391. configurable: true
  7392. });
  7393. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7394. get: function () {
  7395. return this._depthMask;
  7396. },
  7397. set: function (value) {
  7398. if (this._depthMask === value) {
  7399. return;
  7400. }
  7401. this._depthMask = value;
  7402. this._isDepthMaskDirty = true;
  7403. },
  7404. enumerable: true,
  7405. configurable: true
  7406. });
  7407. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7408. get: function () {
  7409. return this._depthTest;
  7410. },
  7411. set: function (value) {
  7412. if (this._depthTest === value) {
  7413. return;
  7414. }
  7415. this._depthTest = value;
  7416. this._isDepthTestDirty = true;
  7417. },
  7418. enumerable: true,
  7419. configurable: true
  7420. });
  7421. _DepthCullingState.prototype.reset = function () {
  7422. this._depthMask = true;
  7423. this._depthTest = true;
  7424. this._depthFunc = null;
  7425. this._cullFace = null;
  7426. this._cull = null;
  7427. this._zOffset = 0;
  7428. this._isDepthTestDirty = true;
  7429. this._isDepthMaskDirty = true;
  7430. this._isDepthFuncDirty = false;
  7431. this._isCullFaceDirty = false;
  7432. this._isCullDirty = false;
  7433. this._isZOffsetDirty = false;
  7434. };
  7435. _DepthCullingState.prototype.apply = function (gl) {
  7436. if (!this.isDirty) {
  7437. return;
  7438. }
  7439. // Cull
  7440. if (this._isCullDirty) {
  7441. if (this.cull) {
  7442. gl.enable(gl.CULL_FACE);
  7443. }
  7444. else {
  7445. gl.disable(gl.CULL_FACE);
  7446. }
  7447. this._isCullDirty = false;
  7448. }
  7449. // Cull face
  7450. if (this._isCullFaceDirty) {
  7451. gl.cullFace(this.cullFace);
  7452. this._isCullFaceDirty = false;
  7453. }
  7454. // Depth mask
  7455. if (this._isDepthMaskDirty) {
  7456. gl.depthMask(this.depthMask);
  7457. this._isDepthMaskDirty = false;
  7458. }
  7459. // Depth test
  7460. if (this._isDepthTestDirty) {
  7461. if (this.depthTest) {
  7462. gl.enable(gl.DEPTH_TEST);
  7463. }
  7464. else {
  7465. gl.disable(gl.DEPTH_TEST);
  7466. }
  7467. this._isDepthTestDirty = false;
  7468. }
  7469. // Depth func
  7470. if (this._isDepthFuncDirty) {
  7471. gl.depthFunc(this.depthFunc);
  7472. this._isDepthFuncDirty = false;
  7473. }
  7474. // zOffset
  7475. if (this._isZOffsetDirty) {
  7476. if (this.zOffset) {
  7477. gl.enable(gl.POLYGON_OFFSET_FILL);
  7478. gl.polygonOffset(this.zOffset, 0);
  7479. }
  7480. else {
  7481. gl.disable(gl.POLYGON_OFFSET_FILL);
  7482. }
  7483. this._isZOffsetDirty = false;
  7484. }
  7485. };
  7486. return _DepthCullingState;
  7487. }());
  7488. Internals._DepthCullingState = _DepthCullingState;
  7489. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7490. })(BABYLON || (BABYLON = {}));
  7491. //# sourceMappingURL=babylon.depthCullingState.js.map
  7492. var BABYLON;
  7493. (function (BABYLON) {
  7494. var Internals;
  7495. (function (Internals) {
  7496. var _StencilState = /** @class */ (function () {
  7497. function _StencilState() {
  7498. this._isStencilTestDirty = false;
  7499. this._isStencilMaskDirty = false;
  7500. this._isStencilFuncDirty = false;
  7501. this._isStencilOpDirty = false;
  7502. this.reset();
  7503. }
  7504. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7505. get: function () {
  7506. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7507. },
  7508. enumerable: true,
  7509. configurable: true
  7510. });
  7511. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7512. get: function () {
  7513. return this._stencilFunc;
  7514. },
  7515. set: function (value) {
  7516. if (this._stencilFunc === value) {
  7517. return;
  7518. }
  7519. this._stencilFunc = value;
  7520. this._isStencilFuncDirty = true;
  7521. },
  7522. enumerable: true,
  7523. configurable: true
  7524. });
  7525. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7526. get: function () {
  7527. return this._stencilFuncRef;
  7528. },
  7529. set: function (value) {
  7530. if (this._stencilFuncRef === value) {
  7531. return;
  7532. }
  7533. this._stencilFuncRef = value;
  7534. this._isStencilFuncDirty = true;
  7535. },
  7536. enumerable: true,
  7537. configurable: true
  7538. });
  7539. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7540. get: function () {
  7541. return this._stencilFuncMask;
  7542. },
  7543. set: function (value) {
  7544. if (this._stencilFuncMask === value) {
  7545. return;
  7546. }
  7547. this._stencilFuncMask = value;
  7548. this._isStencilFuncDirty = true;
  7549. },
  7550. enumerable: true,
  7551. configurable: true
  7552. });
  7553. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7554. get: function () {
  7555. return this._stencilOpStencilFail;
  7556. },
  7557. set: function (value) {
  7558. if (this._stencilOpStencilFail === value) {
  7559. return;
  7560. }
  7561. this._stencilOpStencilFail = value;
  7562. this._isStencilOpDirty = true;
  7563. },
  7564. enumerable: true,
  7565. configurable: true
  7566. });
  7567. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7568. get: function () {
  7569. return this._stencilOpDepthFail;
  7570. },
  7571. set: function (value) {
  7572. if (this._stencilOpDepthFail === value) {
  7573. return;
  7574. }
  7575. this._stencilOpDepthFail = value;
  7576. this._isStencilOpDirty = true;
  7577. },
  7578. enumerable: true,
  7579. configurable: true
  7580. });
  7581. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7582. get: function () {
  7583. return this._stencilOpStencilDepthPass;
  7584. },
  7585. set: function (value) {
  7586. if (this._stencilOpStencilDepthPass === value) {
  7587. return;
  7588. }
  7589. this._stencilOpStencilDepthPass = value;
  7590. this._isStencilOpDirty = true;
  7591. },
  7592. enumerable: true,
  7593. configurable: true
  7594. });
  7595. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7596. get: function () {
  7597. return this._stencilMask;
  7598. },
  7599. set: function (value) {
  7600. if (this._stencilMask === value) {
  7601. return;
  7602. }
  7603. this._stencilMask = value;
  7604. this._isStencilMaskDirty = true;
  7605. },
  7606. enumerable: true,
  7607. configurable: true
  7608. });
  7609. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7610. get: function () {
  7611. return this._stencilTest;
  7612. },
  7613. set: function (value) {
  7614. if (this._stencilTest === value) {
  7615. return;
  7616. }
  7617. this._stencilTest = value;
  7618. this._isStencilTestDirty = true;
  7619. },
  7620. enumerable: true,
  7621. configurable: true
  7622. });
  7623. _StencilState.prototype.reset = function () {
  7624. this._stencilTest = false;
  7625. this._stencilMask = 0xFF;
  7626. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7627. this._stencilFuncRef = 1;
  7628. this._stencilFuncMask = 0xFF;
  7629. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7630. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7631. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7632. this._isStencilTestDirty = true;
  7633. this._isStencilMaskDirty = true;
  7634. this._isStencilFuncDirty = true;
  7635. this._isStencilOpDirty = true;
  7636. };
  7637. _StencilState.prototype.apply = function (gl) {
  7638. if (!this.isDirty) {
  7639. return;
  7640. }
  7641. // Stencil test
  7642. if (this._isStencilTestDirty) {
  7643. if (this.stencilTest) {
  7644. gl.enable(gl.STENCIL_TEST);
  7645. }
  7646. else {
  7647. gl.disable(gl.STENCIL_TEST);
  7648. }
  7649. this._isStencilTestDirty = false;
  7650. }
  7651. // Stencil mask
  7652. if (this._isStencilMaskDirty) {
  7653. gl.stencilMask(this.stencilMask);
  7654. this._isStencilMaskDirty = false;
  7655. }
  7656. // Stencil func
  7657. if (this._isStencilFuncDirty) {
  7658. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7659. this._isStencilFuncDirty = false;
  7660. }
  7661. // Stencil op
  7662. if (this._isStencilOpDirty) {
  7663. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7664. this._isStencilOpDirty = false;
  7665. }
  7666. };
  7667. return _StencilState;
  7668. }());
  7669. Internals._StencilState = _StencilState;
  7670. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7671. })(BABYLON || (BABYLON = {}));
  7672. //# sourceMappingURL=babylon.stencilState.js.map
  7673. var BABYLON;
  7674. (function (BABYLON) {
  7675. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7676. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  7677. };
  7678. var compileRawShader = function (gl, source, type) {
  7679. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7680. gl.shaderSource(shader, source);
  7681. gl.compileShader(shader);
  7682. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7683. var log = gl.getShaderInfoLog(shader);
  7684. if (log) {
  7685. throw new Error(log);
  7686. }
  7687. }
  7688. if (!shader) {
  7689. throw new Error("Something went wrong while compile the shader.");
  7690. }
  7691. return shader;
  7692. };
  7693. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7694. var magFilter = gl.NEAREST;
  7695. var minFilter = gl.NEAREST;
  7696. switch (samplingMode) {
  7697. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7698. magFilter = gl.LINEAR;
  7699. if (generateMipMaps) {
  7700. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7701. }
  7702. else {
  7703. minFilter = gl.LINEAR;
  7704. }
  7705. break;
  7706. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7707. magFilter = gl.LINEAR;
  7708. if (generateMipMaps) {
  7709. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7710. }
  7711. else {
  7712. minFilter = gl.LINEAR;
  7713. }
  7714. break;
  7715. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7716. magFilter = gl.NEAREST;
  7717. if (generateMipMaps) {
  7718. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7719. }
  7720. else {
  7721. minFilter = gl.NEAREST;
  7722. }
  7723. break;
  7724. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7725. magFilter = gl.NEAREST;
  7726. if (generateMipMaps) {
  7727. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7728. }
  7729. else {
  7730. minFilter = gl.NEAREST;
  7731. }
  7732. break;
  7733. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7734. magFilter = gl.NEAREST;
  7735. if (generateMipMaps) {
  7736. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7737. }
  7738. else {
  7739. minFilter = gl.LINEAR;
  7740. }
  7741. break;
  7742. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7743. magFilter = gl.NEAREST;
  7744. if (generateMipMaps) {
  7745. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7746. }
  7747. else {
  7748. minFilter = gl.LINEAR;
  7749. }
  7750. break;
  7751. case BABYLON.Texture.NEAREST_LINEAR:
  7752. magFilter = gl.NEAREST;
  7753. minFilter = gl.LINEAR;
  7754. break;
  7755. case BABYLON.Texture.NEAREST_NEAREST:
  7756. magFilter = gl.NEAREST;
  7757. minFilter = gl.NEAREST;
  7758. break;
  7759. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7760. magFilter = gl.LINEAR;
  7761. if (generateMipMaps) {
  7762. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7763. }
  7764. else {
  7765. minFilter = gl.NEAREST;
  7766. }
  7767. break;
  7768. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7769. magFilter = gl.LINEAR;
  7770. if (generateMipMaps) {
  7771. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7772. }
  7773. else {
  7774. minFilter = gl.NEAREST;
  7775. }
  7776. break;
  7777. case BABYLON.Texture.LINEAR_LINEAR:
  7778. magFilter = gl.LINEAR;
  7779. minFilter = gl.LINEAR;
  7780. break;
  7781. case BABYLON.Texture.LINEAR_NEAREST:
  7782. magFilter = gl.LINEAR;
  7783. minFilter = gl.NEAREST;
  7784. break;
  7785. }
  7786. return {
  7787. min: minFilter,
  7788. mag: magFilter
  7789. };
  7790. };
  7791. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7792. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7793. var img;
  7794. var onload = function () {
  7795. loadedImages[index] = img;
  7796. loadedImages._internalCount++;
  7797. if (scene) {
  7798. scene._removePendingData(img);
  7799. }
  7800. if (loadedImages._internalCount === 6) {
  7801. onfinish(loadedImages);
  7802. }
  7803. };
  7804. var onerror = function (message, exception) {
  7805. if (scene) {
  7806. scene._removePendingData(img);
  7807. }
  7808. if (onErrorCallBack) {
  7809. onErrorCallBack(message, exception);
  7810. }
  7811. };
  7812. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7813. if (scene) {
  7814. scene._addPendingData(img);
  7815. }
  7816. };
  7817. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  7818. if (onError === void 0) { onError = null; }
  7819. var loadedImages = [];
  7820. loadedImages._internalCount = 0;
  7821. for (var index = 0; index < 6; index++) {
  7822. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  7823. }
  7824. };
  7825. var partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  7826. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7827. var onload = function (data) {
  7828. loadedFiles[index] = data;
  7829. loadedFiles._internalCount++;
  7830. if (loadedFiles._internalCount === 6) {
  7831. onfinish(loadedFiles);
  7832. }
  7833. };
  7834. var onerror = function (request, exception) {
  7835. if (onErrorCallBack) {
  7836. onErrorCallBack(request.status + " " + request.statusText, exception);
  7837. }
  7838. };
  7839. BABYLON.Tools.LoadFile(url, onload, undefined, undefined, true, onerror);
  7840. };
  7841. var cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  7842. if (onError === void 0) { onError = null; }
  7843. var loadedFiles = [];
  7844. loadedFiles._internalCount = 0;
  7845. for (var index = 0; index < 6; index++) {
  7846. partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  7847. }
  7848. };
  7849. var BufferPointer = /** @class */ (function () {
  7850. function BufferPointer() {
  7851. }
  7852. return BufferPointer;
  7853. }());
  7854. var InstancingAttributeInfo = /** @class */ (function () {
  7855. function InstancingAttributeInfo() {
  7856. }
  7857. return InstancingAttributeInfo;
  7858. }());
  7859. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7860. /**
  7861. * Define options used to create a render target texture
  7862. */
  7863. var RenderTargetCreationOptions = /** @class */ (function () {
  7864. function RenderTargetCreationOptions() {
  7865. }
  7866. return RenderTargetCreationOptions;
  7867. }());
  7868. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7869. /**
  7870. * Regroup several parameters relative to the browser in use
  7871. */
  7872. var EngineCapabilities = /** @class */ (function () {
  7873. function EngineCapabilities() {
  7874. }
  7875. return EngineCapabilities;
  7876. }());
  7877. BABYLON.EngineCapabilities = EngineCapabilities;
  7878. /**
  7879. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7880. */
  7881. var Engine = /** @class */ (function () {
  7882. /**
  7883. * @constructor
  7884. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7885. * @param {boolean} [antialias] - enable antialias
  7886. * @param options - further options to be sent to the getContext function
  7887. */
  7888. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7889. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7890. var _this = this;
  7891. // Public members
  7892. this.forcePOTTextures = false;
  7893. this.isFullscreen = false;
  7894. this.isPointerLock = false;
  7895. this.cullBackFaces = true;
  7896. this.renderEvenInBackground = true;
  7897. this.preventCacheWipeBetweenFrames = false;
  7898. // To enable/disable IDB support and avoid XHR on .manifest
  7899. this.enableOfflineSupport = false;
  7900. this.scenes = new Array();
  7901. this.postProcesses = new Array();
  7902. // Observables
  7903. /**
  7904. * Observable event triggered each time the rendering canvas is resized
  7905. */
  7906. this.onResizeObservable = new BABYLON.Observable();
  7907. /**
  7908. * Observable event triggered each time the canvas loses focus
  7909. */
  7910. this.onCanvasBlurObservable = new BABYLON.Observable();
  7911. /**
  7912. * Observable event triggered each time the canvas gains focus
  7913. */
  7914. this.onCanvasFocusObservable = new BABYLON.Observable();
  7915. /**
  7916. * Observable event triggered each time the canvas receives pointerout event
  7917. */
  7918. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  7919. /**
  7920. * Observable event triggered before each texture is initialized
  7921. */
  7922. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  7923. //WebVR
  7924. this._vrDisplay = undefined;
  7925. this._vrSupported = false;
  7926. this._vrExclusivePointerMode = false;
  7927. // Uniform buffers list
  7928. this.disableUniformBuffers = false;
  7929. this._uniformBuffers = new Array();
  7930. // Observables
  7931. /**
  7932. * Observable raised when the engine begins a new frame
  7933. */
  7934. this.onBeginFrameObservable = new BABYLON.Observable();
  7935. /**
  7936. * Observable raised when the engine ends the current frame
  7937. */
  7938. this.onEndFrameObservable = new BABYLON.Observable();
  7939. /**
  7940. * Observable raised when the engine is about to compile a shader
  7941. */
  7942. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  7943. /**
  7944. * Observable raised when the engine has jsut compiled a shader
  7945. */
  7946. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  7947. this._windowIsBackground = false;
  7948. this._webGLVersion = 1.0;
  7949. this._badOS = false;
  7950. this._badDesktopOS = false;
  7951. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  7952. this.onVRRequestPresentComplete = new BABYLON.Observable();
  7953. this.onVRRequestPresentStart = new BABYLON.Observable();
  7954. this._colorWrite = true;
  7955. this._drawCalls = new BABYLON.PerfCounter();
  7956. this._renderingQueueLaunched = false;
  7957. this._activeRenderLoops = new Array();
  7958. // Deterministic lockstepMaxSteps
  7959. this._deterministicLockstep = false;
  7960. this._lockstepMaxSteps = 4;
  7961. // Lost context
  7962. this.onContextLostObservable = new BABYLON.Observable();
  7963. this.onContextRestoredObservable = new BABYLON.Observable();
  7964. this._contextWasLost = false;
  7965. this._doNotHandleContextLost = false;
  7966. // FPS
  7967. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7968. this._fps = 60;
  7969. this._deltaTime = 0;
  7970. /**
  7971. * Turn this value on if you want to pause FPS computation when in background
  7972. */
  7973. this.disablePerformanceMonitorInBackground = false;
  7974. // States
  7975. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7976. this._stencilState = new BABYLON.Internals._StencilState();
  7977. this._alphaState = new BABYLON.Internals._AlphaState();
  7978. this._alphaMode = Engine.ALPHA_DISABLE;
  7979. // Cache
  7980. this._internalTexturesCache = new Array();
  7981. this._activeTexturesCache = {};
  7982. this._compiledEffects = {};
  7983. this._vertexAttribArraysEnabled = [];
  7984. this._uintIndicesCurrentlySet = false;
  7985. this._currentBoundBuffer = new Array();
  7986. this._currentBufferPointers = new Array();
  7987. this._currentInstanceLocations = new Array();
  7988. this._currentInstanceBuffers = new Array();
  7989. this._vaoRecordInProgress = false;
  7990. this._mustWipeVertexAttributes = false;
  7991. // Hardware supported Compressed Textures
  7992. this._texturesSupported = new Array();
  7993. this._onVRFullScreenTriggered = function () {
  7994. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  7995. //get the old size before we change
  7996. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7997. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7998. //get the width and height, change the render size
  7999. var leftEye = _this._vrDisplay.getEyeParameters('left');
  8000. _this.setHardwareScalingLevel(1);
  8001. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  8002. }
  8003. else {
  8004. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  8005. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  8006. }
  8007. };
  8008. var canvas = null;
  8009. Engine.Instances.push(this);
  8010. if (!canvasOrContext) {
  8011. return;
  8012. }
  8013. options = options || {};
  8014. if (canvasOrContext.getContext) {
  8015. canvas = canvasOrContext;
  8016. this._renderingCanvas = canvas;
  8017. if (antialias != null) {
  8018. options.antialias = antialias;
  8019. }
  8020. if (options.deterministicLockstep === undefined) {
  8021. options.deterministicLockstep = false;
  8022. }
  8023. if (options.lockstepMaxSteps === undefined) {
  8024. options.lockstepMaxSteps = 4;
  8025. }
  8026. if (options.preserveDrawingBuffer === undefined) {
  8027. options.preserveDrawingBuffer = false;
  8028. }
  8029. if (options.audioEngine === undefined) {
  8030. options.audioEngine = true;
  8031. }
  8032. if (options.stencil === undefined) {
  8033. options.stencil = true;
  8034. }
  8035. this._deterministicLockstep = options.deterministicLockstep;
  8036. this._lockstepMaxSteps = options.lockstepMaxSteps;
  8037. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  8038. // GL
  8039. if (!options.disableWebGL2Support) {
  8040. try {
  8041. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  8042. if (this._gl) {
  8043. this._webGLVersion = 2.0;
  8044. }
  8045. }
  8046. catch (e) {
  8047. // Do nothing
  8048. }
  8049. }
  8050. if (!this._gl) {
  8051. if (!canvas) {
  8052. throw new Error("The provided canvas is null or undefined.");
  8053. }
  8054. try {
  8055. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  8056. }
  8057. catch (e) {
  8058. throw new Error("WebGL not supported");
  8059. }
  8060. }
  8061. if (!this._gl) {
  8062. throw new Error("WebGL not supported");
  8063. }
  8064. this._onCanvasFocus = function () {
  8065. _this.onCanvasFocusObservable.notifyObservers(_this);
  8066. };
  8067. this._onCanvasBlur = function () {
  8068. _this.onCanvasBlurObservable.notifyObservers(_this);
  8069. };
  8070. canvas.addEventListener("focus", this._onCanvasFocus);
  8071. canvas.addEventListener("blur", this._onCanvasBlur);
  8072. this._onBlur = function () {
  8073. if (_this.disablePerformanceMonitorInBackground) {
  8074. _this._performanceMonitor.disable();
  8075. }
  8076. _this._windowIsBackground = true;
  8077. };
  8078. this._onFocus = function () {
  8079. if (_this.disablePerformanceMonitorInBackground) {
  8080. _this._performanceMonitor.enable();
  8081. }
  8082. _this._windowIsBackground = false;
  8083. };
  8084. this._onCanvasPointerOut = function () {
  8085. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  8086. };
  8087. window.addEventListener("blur", this._onBlur);
  8088. window.addEventListener("focus", this._onFocus);
  8089. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  8090. // Context lost
  8091. if (!this._doNotHandleContextLost) {
  8092. this._onContextLost = function (evt) {
  8093. evt.preventDefault();
  8094. _this._contextWasLost = true;
  8095. BABYLON.Tools.Warn("WebGL context lost.");
  8096. _this.onContextLostObservable.notifyObservers(_this);
  8097. };
  8098. this._onContextRestored = function (evt) {
  8099. // Adding a timeout to avoid race condition at browser level
  8100. setTimeout(function () {
  8101. // Rebuild gl context
  8102. _this._initGLContext();
  8103. // Rebuild effects
  8104. _this._rebuildEffects();
  8105. // Rebuild textures
  8106. _this._rebuildInternalTextures();
  8107. // Rebuild buffers
  8108. _this._rebuildBuffers();
  8109. // Cache
  8110. _this.wipeCaches(true);
  8111. BABYLON.Tools.Warn("WebGL context successfully restored.");
  8112. _this.onContextRestoredObservable.notifyObservers(_this);
  8113. _this._contextWasLost = false;
  8114. }, 0);
  8115. };
  8116. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  8117. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  8118. }
  8119. }
  8120. else {
  8121. this._gl = canvasOrContext;
  8122. this._renderingCanvas = this._gl.canvas;
  8123. if (this._gl.renderbufferStorageMultisample) {
  8124. this._webGLVersion = 2.0;
  8125. }
  8126. options.stencil = this._gl.getContextAttributes().stencil;
  8127. }
  8128. // Viewport
  8129. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  8130. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  8131. this.resize();
  8132. this._isStencilEnable = options.stencil ? true : false;
  8133. this._initGLContext();
  8134. if (canvas) {
  8135. // Fullscreen
  8136. this._onFullscreenChange = function () {
  8137. if (document.fullscreen !== undefined) {
  8138. _this.isFullscreen = document.fullscreen;
  8139. }
  8140. else if (document.mozFullScreen !== undefined) {
  8141. _this.isFullscreen = document.mozFullScreen;
  8142. }
  8143. else if (document.webkitIsFullScreen !== undefined) {
  8144. _this.isFullscreen = document.webkitIsFullScreen;
  8145. }
  8146. else if (document.msIsFullScreen !== undefined) {
  8147. _this.isFullscreen = document.msIsFullScreen;
  8148. }
  8149. // Pointer lock
  8150. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  8151. canvas.requestPointerLock = canvas.requestPointerLock ||
  8152. canvas.msRequestPointerLock ||
  8153. canvas.mozRequestPointerLock ||
  8154. canvas.webkitRequestPointerLock;
  8155. if (canvas.requestPointerLock) {
  8156. canvas.requestPointerLock();
  8157. }
  8158. }
  8159. };
  8160. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8161. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8162. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8163. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8164. // Pointer lock
  8165. this._onPointerLockChange = function () {
  8166. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8167. document.webkitPointerLockElement === canvas ||
  8168. document.msPointerLockElement === canvas ||
  8169. document.pointerLockElement === canvas);
  8170. };
  8171. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8172. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8173. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8174. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8175. this._onVRDisplayPointerRestricted = function () {
  8176. if (canvas) {
  8177. canvas.requestPointerLock();
  8178. }
  8179. };
  8180. this._onVRDisplayPointerUnrestricted = function () {
  8181. document.exitPointerLock();
  8182. };
  8183. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  8184. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  8185. }
  8186. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  8187. Engine.audioEngine = new BABYLON.AudioEngine();
  8188. }
  8189. // Prepare buffer pointers
  8190. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  8191. this._currentBufferPointers[i] = new BufferPointer();
  8192. }
  8193. // Load WebVR Devices
  8194. if (options.autoEnableWebVR) {
  8195. this.initWebVR();
  8196. }
  8197. // Detect if we are running on a faulty buggy OS.
  8198. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  8199. // Detect if we are running on a faulty buggy desktop OS.
  8200. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  8201. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8202. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  8203. }
  8204. Object.defineProperty(Engine, "LastCreatedEngine", {
  8205. get: function () {
  8206. if (Engine.Instances.length === 0) {
  8207. return null;
  8208. }
  8209. return Engine.Instances[Engine.Instances.length - 1];
  8210. },
  8211. enumerable: true,
  8212. configurable: true
  8213. });
  8214. Object.defineProperty(Engine, "LastCreatedScene", {
  8215. get: function () {
  8216. var lastCreatedEngine = Engine.LastCreatedEngine;
  8217. if (!lastCreatedEngine) {
  8218. return null;
  8219. }
  8220. if (lastCreatedEngine.scenes.length === 0) {
  8221. return null;
  8222. }
  8223. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8224. },
  8225. enumerable: true,
  8226. configurable: true
  8227. });
  8228. /**
  8229. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  8230. */
  8231. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  8232. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  8233. var engine = Engine.Instances[engineIndex];
  8234. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  8235. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  8236. }
  8237. }
  8238. };
  8239. Object.defineProperty(Engine, "NEVER", {
  8240. get: function () {
  8241. return Engine._NEVER;
  8242. },
  8243. enumerable: true,
  8244. configurable: true
  8245. });
  8246. Object.defineProperty(Engine, "ALWAYS", {
  8247. get: function () {
  8248. return Engine._ALWAYS;
  8249. },
  8250. enumerable: true,
  8251. configurable: true
  8252. });
  8253. Object.defineProperty(Engine, "LESS", {
  8254. get: function () {
  8255. return Engine._LESS;
  8256. },
  8257. enumerable: true,
  8258. configurable: true
  8259. });
  8260. Object.defineProperty(Engine, "EQUAL", {
  8261. get: function () {
  8262. return Engine._EQUAL;
  8263. },
  8264. enumerable: true,
  8265. configurable: true
  8266. });
  8267. Object.defineProperty(Engine, "LEQUAL", {
  8268. get: function () {
  8269. return Engine._LEQUAL;
  8270. },
  8271. enumerable: true,
  8272. configurable: true
  8273. });
  8274. Object.defineProperty(Engine, "GREATER", {
  8275. get: function () {
  8276. return Engine._GREATER;
  8277. },
  8278. enumerable: true,
  8279. configurable: true
  8280. });
  8281. Object.defineProperty(Engine, "GEQUAL", {
  8282. get: function () {
  8283. return Engine._GEQUAL;
  8284. },
  8285. enumerable: true,
  8286. configurable: true
  8287. });
  8288. Object.defineProperty(Engine, "NOTEQUAL", {
  8289. get: function () {
  8290. return Engine._NOTEQUAL;
  8291. },
  8292. enumerable: true,
  8293. configurable: true
  8294. });
  8295. Object.defineProperty(Engine, "KEEP", {
  8296. get: function () {
  8297. return Engine._KEEP;
  8298. },
  8299. enumerable: true,
  8300. configurable: true
  8301. });
  8302. Object.defineProperty(Engine, "REPLACE", {
  8303. get: function () {
  8304. return Engine._REPLACE;
  8305. },
  8306. enumerable: true,
  8307. configurable: true
  8308. });
  8309. Object.defineProperty(Engine, "INCR", {
  8310. get: function () {
  8311. return Engine._INCR;
  8312. },
  8313. enumerable: true,
  8314. configurable: true
  8315. });
  8316. Object.defineProperty(Engine, "DECR", {
  8317. get: function () {
  8318. return Engine._DECR;
  8319. },
  8320. enumerable: true,
  8321. configurable: true
  8322. });
  8323. Object.defineProperty(Engine, "INVERT", {
  8324. get: function () {
  8325. return Engine._INVERT;
  8326. },
  8327. enumerable: true,
  8328. configurable: true
  8329. });
  8330. Object.defineProperty(Engine, "INCR_WRAP", {
  8331. get: function () {
  8332. return Engine._INCR_WRAP;
  8333. },
  8334. enumerable: true,
  8335. configurable: true
  8336. });
  8337. Object.defineProperty(Engine, "DECR_WRAP", {
  8338. get: function () {
  8339. return Engine._DECR_WRAP;
  8340. },
  8341. enumerable: true,
  8342. configurable: true
  8343. });
  8344. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8345. get: function () {
  8346. return Engine._ALPHA_DISABLE;
  8347. },
  8348. enumerable: true,
  8349. configurable: true
  8350. });
  8351. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8352. get: function () {
  8353. return Engine._ALPHA_ONEONE;
  8354. },
  8355. enumerable: true,
  8356. configurable: true
  8357. });
  8358. Object.defineProperty(Engine, "ALPHA_ADD", {
  8359. get: function () {
  8360. return Engine._ALPHA_ADD;
  8361. },
  8362. enumerable: true,
  8363. configurable: true
  8364. });
  8365. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8366. get: function () {
  8367. return Engine._ALPHA_COMBINE;
  8368. },
  8369. enumerable: true,
  8370. configurable: true
  8371. });
  8372. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8373. get: function () {
  8374. return Engine._ALPHA_SUBTRACT;
  8375. },
  8376. enumerable: true,
  8377. configurable: true
  8378. });
  8379. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8380. get: function () {
  8381. return Engine._ALPHA_MULTIPLY;
  8382. },
  8383. enumerable: true,
  8384. configurable: true
  8385. });
  8386. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8387. get: function () {
  8388. return Engine._ALPHA_MAXIMIZED;
  8389. },
  8390. enumerable: true,
  8391. configurable: true
  8392. });
  8393. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8394. get: function () {
  8395. return Engine._ALPHA_PREMULTIPLIED;
  8396. },
  8397. enumerable: true,
  8398. configurable: true
  8399. });
  8400. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8401. get: function () {
  8402. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8403. },
  8404. enumerable: true,
  8405. configurable: true
  8406. });
  8407. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8408. get: function () {
  8409. return Engine._ALPHA_INTERPOLATE;
  8410. },
  8411. enumerable: true,
  8412. configurable: true
  8413. });
  8414. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8415. get: function () {
  8416. return Engine._ALPHA_SCREENMODE;
  8417. },
  8418. enumerable: true,
  8419. configurable: true
  8420. });
  8421. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8422. get: function () {
  8423. return Engine._DELAYLOADSTATE_NONE;
  8424. },
  8425. enumerable: true,
  8426. configurable: true
  8427. });
  8428. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8429. get: function () {
  8430. return Engine._DELAYLOADSTATE_LOADED;
  8431. },
  8432. enumerable: true,
  8433. configurable: true
  8434. });
  8435. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8436. get: function () {
  8437. return Engine._DELAYLOADSTATE_LOADING;
  8438. },
  8439. enumerable: true,
  8440. configurable: true
  8441. });
  8442. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8443. get: function () {
  8444. return Engine._DELAYLOADSTATE_NOTLOADED;
  8445. },
  8446. enumerable: true,
  8447. configurable: true
  8448. });
  8449. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8450. get: function () {
  8451. return Engine._TEXTUREFORMAT_ALPHA;
  8452. },
  8453. enumerable: true,
  8454. configurable: true
  8455. });
  8456. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8457. get: function () {
  8458. return Engine._TEXTUREFORMAT_LUMINANCE;
  8459. },
  8460. enumerable: true,
  8461. configurable: true
  8462. });
  8463. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8464. get: function () {
  8465. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8466. },
  8467. enumerable: true,
  8468. configurable: true
  8469. });
  8470. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8471. get: function () {
  8472. return Engine._TEXTUREFORMAT_RGB;
  8473. },
  8474. enumerable: true,
  8475. configurable: true
  8476. });
  8477. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8478. get: function () {
  8479. return Engine._TEXTUREFORMAT_RGBA;
  8480. },
  8481. enumerable: true,
  8482. configurable: true
  8483. });
  8484. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8485. get: function () {
  8486. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8487. },
  8488. enumerable: true,
  8489. configurable: true
  8490. });
  8491. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8492. get: function () {
  8493. return Engine._TEXTURETYPE_FLOAT;
  8494. },
  8495. enumerable: true,
  8496. configurable: true
  8497. });
  8498. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8499. get: function () {
  8500. return Engine._TEXTURETYPE_HALF_FLOAT;
  8501. },
  8502. enumerable: true,
  8503. configurable: true
  8504. });
  8505. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8506. get: function () {
  8507. return Engine._SCALEMODE_FLOOR;
  8508. },
  8509. enumerable: true,
  8510. configurable: true
  8511. });
  8512. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8513. get: function () {
  8514. return Engine._SCALEMODE_NEAREST;
  8515. },
  8516. enumerable: true,
  8517. configurable: true
  8518. });
  8519. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8520. get: function () {
  8521. return Engine._SCALEMODE_CEILING;
  8522. },
  8523. enumerable: true,
  8524. configurable: true
  8525. });
  8526. Object.defineProperty(Engine, "Version", {
  8527. get: function () {
  8528. return "3.1-beta-5";
  8529. },
  8530. enumerable: true,
  8531. configurable: true
  8532. });
  8533. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  8534. get: function () {
  8535. return this._vrExclusivePointerMode;
  8536. },
  8537. enumerable: true,
  8538. configurable: true
  8539. });
  8540. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8541. get: function () {
  8542. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8543. },
  8544. enumerable: true,
  8545. configurable: true
  8546. });
  8547. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8548. get: function () {
  8549. return this._webGLVersion < 2 || this.forcePOTTextures;
  8550. },
  8551. enumerable: true,
  8552. configurable: true
  8553. });
  8554. Object.defineProperty(Engine.prototype, "badOS", {
  8555. get: function () {
  8556. return this._badOS;
  8557. },
  8558. enumerable: true,
  8559. configurable: true
  8560. });
  8561. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8562. get: function () {
  8563. return this._badDesktopOS;
  8564. },
  8565. enumerable: true,
  8566. configurable: true
  8567. });
  8568. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8569. get: function () {
  8570. return this._performanceMonitor;
  8571. },
  8572. enumerable: true,
  8573. configurable: true
  8574. });
  8575. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8576. get: function () {
  8577. return this._texturesSupported;
  8578. },
  8579. enumerable: true,
  8580. configurable: true
  8581. });
  8582. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8583. get: function () {
  8584. return this._textureFormatInUse;
  8585. },
  8586. enumerable: true,
  8587. configurable: true
  8588. });
  8589. Object.defineProperty(Engine.prototype, "currentViewport", {
  8590. get: function () {
  8591. return this._cachedViewport;
  8592. },
  8593. enumerable: true,
  8594. configurable: true
  8595. });
  8596. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8597. // Empty texture
  8598. get: function () {
  8599. if (!this._emptyTexture) {
  8600. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8601. }
  8602. return this._emptyTexture;
  8603. },
  8604. enumerable: true,
  8605. configurable: true
  8606. });
  8607. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  8608. get: function () {
  8609. if (!this._emptyTexture3D) {
  8610. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8611. }
  8612. return this._emptyTexture3D;
  8613. },
  8614. enumerable: true,
  8615. configurable: true
  8616. });
  8617. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8618. get: function () {
  8619. if (!this._emptyCubeTexture) {
  8620. var faceData = new Uint8Array(4);
  8621. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8622. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8623. }
  8624. return this._emptyCubeTexture;
  8625. },
  8626. enumerable: true,
  8627. configurable: true
  8628. });
  8629. Engine.prototype._rebuildInternalTextures = function () {
  8630. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8631. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8632. var internalTexture = currentState_1[_i];
  8633. internalTexture._rebuild();
  8634. }
  8635. };
  8636. Engine.prototype._rebuildEffects = function () {
  8637. for (var key in this._compiledEffects) {
  8638. var effect = this._compiledEffects[key];
  8639. effect._prepareEffect();
  8640. }
  8641. BABYLON.Effect.ResetCache();
  8642. };
  8643. Engine.prototype._rebuildBuffers = function () {
  8644. // Index / Vertex
  8645. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8646. var scene = _a[_i];
  8647. scene.resetCachedMaterial();
  8648. scene._rebuildGeometries();
  8649. scene._rebuildTextures();
  8650. }
  8651. // Uniforms
  8652. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8653. var uniformBuffer = _c[_b];
  8654. uniformBuffer._rebuild();
  8655. }
  8656. };
  8657. Engine.prototype._initGLContext = function () {
  8658. // Caps
  8659. this._caps = new EngineCapabilities();
  8660. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8661. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8662. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8663. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8664. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8665. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8666. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8667. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8668. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8669. // Infos
  8670. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8671. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8672. if (rendererInfo != null) {
  8673. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8674. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8675. }
  8676. if (!this._glVendor) {
  8677. this._glVendor = "Unknown vendor";
  8678. }
  8679. if (!this._glRenderer) {
  8680. this._glRenderer = "Unknown renderer";
  8681. }
  8682. // Constants
  8683. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8684. if (this._gl.RGBA16F !== 0x881A) {
  8685. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8686. }
  8687. if (this._gl.RGBA32F !== 0x8814) {
  8688. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8689. }
  8690. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  8691. this._gl.DEPTH24_STENCIL8 = 35056;
  8692. }
  8693. // Extensions
  8694. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8695. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8696. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8697. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8698. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8699. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8700. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8701. 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');
  8702. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8703. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8704. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8705. this._caps.highPrecisionShaderSupported = true;
  8706. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  8707. if (this._caps.timerQuery) {
  8708. if (this._webGLVersion === 1) {
  8709. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  8710. }
  8711. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  8712. }
  8713. // Checks if some of the format renders first to allow the use of webgl inspector.
  8714. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8715. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8716. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8717. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8718. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8719. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8720. if (this._webGLVersion > 1) {
  8721. this._gl.HALF_FLOAT_OES = 0x140B;
  8722. }
  8723. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8724. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8725. // Draw buffers
  8726. if (this._webGLVersion > 1) {
  8727. this._caps.drawBuffersExtension = true;
  8728. }
  8729. else {
  8730. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8731. if (drawBuffersExtension !== null) {
  8732. this._caps.drawBuffersExtension = true;
  8733. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8734. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8735. for (var i = 0; i < 16; i++) {
  8736. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8737. }
  8738. }
  8739. else {
  8740. this._caps.drawBuffersExtension = false;
  8741. }
  8742. }
  8743. // Depth Texture
  8744. if (this._webGLVersion > 1) {
  8745. this._caps.depthTextureExtension = true;
  8746. }
  8747. else {
  8748. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8749. if (depthTextureExtension != null) {
  8750. this._caps.depthTextureExtension = true;
  8751. }
  8752. }
  8753. // Vertex array object
  8754. if (this._webGLVersion > 1) {
  8755. this._caps.vertexArrayObject = true;
  8756. }
  8757. else {
  8758. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8759. if (vertexArrayObjectExtension != null) {
  8760. this._caps.vertexArrayObject = true;
  8761. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8762. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8763. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8764. }
  8765. else {
  8766. this._caps.vertexArrayObject = false;
  8767. }
  8768. }
  8769. // Instances count
  8770. if (this._webGLVersion > 1) {
  8771. this._caps.instancedArrays = true;
  8772. }
  8773. else {
  8774. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8775. if (instanceExtension != null) {
  8776. this._caps.instancedArrays = true;
  8777. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8778. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8779. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8780. }
  8781. else {
  8782. this._caps.instancedArrays = false;
  8783. }
  8784. }
  8785. // Intelligently add supported compressed formats in order to check for.
  8786. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8787. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8788. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8789. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8790. if (this._caps.astc)
  8791. this.texturesSupported.push('-astc.ktx');
  8792. if (this._caps.s3tc)
  8793. this.texturesSupported.push('-dxt.ktx');
  8794. if (this._caps.pvrtc)
  8795. this.texturesSupported.push('-pvrtc.ktx');
  8796. if (this._caps.etc2)
  8797. this.texturesSupported.push('-etc2.ktx');
  8798. if (this._caps.etc1)
  8799. this.texturesSupported.push('-etc1.ktx');
  8800. if (this._gl.getShaderPrecisionFormat) {
  8801. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8802. if (highp) {
  8803. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8804. }
  8805. }
  8806. // Depth buffer
  8807. this.setDepthBuffer(true);
  8808. this.setDepthFunctionToLessOrEqual();
  8809. this.setDepthWrite(true);
  8810. };
  8811. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8812. get: function () {
  8813. return this._webGLVersion;
  8814. },
  8815. enumerable: true,
  8816. configurable: true
  8817. });
  8818. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8819. /**
  8820. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8821. */
  8822. get: function () {
  8823. return this._isStencilEnable;
  8824. },
  8825. enumerable: true,
  8826. configurable: true
  8827. });
  8828. Engine.prototype._prepareWorkingCanvas = function () {
  8829. if (this._workingCanvas) {
  8830. return;
  8831. }
  8832. this._workingCanvas = document.createElement("canvas");
  8833. var context = this._workingCanvas.getContext("2d");
  8834. if (context) {
  8835. this._workingContext = context;
  8836. }
  8837. };
  8838. Engine.prototype.resetTextureCache = function () {
  8839. for (var key in this._activeTexturesCache) {
  8840. this._activeTexturesCache[key] = null;
  8841. }
  8842. };
  8843. Engine.prototype.isDeterministicLockStep = function () {
  8844. return this._deterministicLockstep;
  8845. };
  8846. Engine.prototype.getLockstepMaxSteps = function () {
  8847. return this._lockstepMaxSteps;
  8848. };
  8849. Engine.prototype.getGlInfo = function () {
  8850. return {
  8851. vendor: this._glVendor,
  8852. renderer: this._glRenderer,
  8853. version: this._glVersion
  8854. };
  8855. };
  8856. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8857. if (useScreen === void 0) { useScreen = false; }
  8858. var viewport = camera.viewport;
  8859. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8860. };
  8861. Engine.prototype.getRenderWidth = function (useScreen) {
  8862. if (useScreen === void 0) { useScreen = false; }
  8863. if (!useScreen && this._currentRenderTarget) {
  8864. return this._currentRenderTarget.width;
  8865. }
  8866. return this._gl.drawingBufferWidth;
  8867. };
  8868. Engine.prototype.getRenderHeight = function (useScreen) {
  8869. if (useScreen === void 0) { useScreen = false; }
  8870. if (!useScreen && this._currentRenderTarget) {
  8871. return this._currentRenderTarget.height;
  8872. }
  8873. return this._gl.drawingBufferHeight;
  8874. };
  8875. Engine.prototype.getRenderingCanvas = function () {
  8876. return this._renderingCanvas;
  8877. };
  8878. Engine.prototype.getRenderingCanvasClientRect = function () {
  8879. if (!this._renderingCanvas) {
  8880. return null;
  8881. }
  8882. return this._renderingCanvas.getBoundingClientRect();
  8883. };
  8884. Engine.prototype.setHardwareScalingLevel = function (level) {
  8885. this._hardwareScalingLevel = level;
  8886. this.resize();
  8887. };
  8888. Engine.prototype.getHardwareScalingLevel = function () {
  8889. return this._hardwareScalingLevel;
  8890. };
  8891. Engine.prototype.getLoadedTexturesCache = function () {
  8892. return this._internalTexturesCache;
  8893. };
  8894. Engine.prototype.getCaps = function () {
  8895. return this._caps;
  8896. };
  8897. Object.defineProperty(Engine.prototype, "drawCalls", {
  8898. /** The number of draw calls submitted last frame */
  8899. get: function () {
  8900. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  8901. return 0;
  8902. },
  8903. enumerable: true,
  8904. configurable: true
  8905. });
  8906. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8907. get: function () {
  8908. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  8909. return null;
  8910. },
  8911. enumerable: true,
  8912. configurable: true
  8913. });
  8914. Engine.prototype.getDepthFunction = function () {
  8915. return this._depthCullingState.depthFunc;
  8916. };
  8917. Engine.prototype.setDepthFunction = function (depthFunc) {
  8918. this._depthCullingState.depthFunc = depthFunc;
  8919. };
  8920. Engine.prototype.setDepthFunctionToGreater = function () {
  8921. this._depthCullingState.depthFunc = this._gl.GREATER;
  8922. };
  8923. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8924. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8925. };
  8926. Engine.prototype.setDepthFunctionToLess = function () {
  8927. this._depthCullingState.depthFunc = this._gl.LESS;
  8928. };
  8929. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8930. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8931. };
  8932. Engine.prototype.getStencilBuffer = function () {
  8933. return this._stencilState.stencilTest;
  8934. };
  8935. Engine.prototype.setStencilBuffer = function (enable) {
  8936. this._stencilState.stencilTest = enable;
  8937. };
  8938. Engine.prototype.getStencilMask = function () {
  8939. return this._stencilState.stencilMask;
  8940. };
  8941. Engine.prototype.setStencilMask = function (mask) {
  8942. this._stencilState.stencilMask = mask;
  8943. };
  8944. Engine.prototype.getStencilFunction = function () {
  8945. return this._stencilState.stencilFunc;
  8946. };
  8947. Engine.prototype.getStencilFunctionReference = function () {
  8948. return this._stencilState.stencilFuncRef;
  8949. };
  8950. Engine.prototype.getStencilFunctionMask = function () {
  8951. return this._stencilState.stencilFuncMask;
  8952. };
  8953. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8954. this._stencilState.stencilFunc = stencilFunc;
  8955. };
  8956. Engine.prototype.setStencilFunctionReference = function (reference) {
  8957. this._stencilState.stencilFuncRef = reference;
  8958. };
  8959. Engine.prototype.setStencilFunctionMask = function (mask) {
  8960. this._stencilState.stencilFuncMask = mask;
  8961. };
  8962. Engine.prototype.getStencilOperationFail = function () {
  8963. return this._stencilState.stencilOpStencilFail;
  8964. };
  8965. Engine.prototype.getStencilOperationDepthFail = function () {
  8966. return this._stencilState.stencilOpDepthFail;
  8967. };
  8968. Engine.prototype.getStencilOperationPass = function () {
  8969. return this._stencilState.stencilOpStencilDepthPass;
  8970. };
  8971. Engine.prototype.setStencilOperationFail = function (operation) {
  8972. this._stencilState.stencilOpStencilFail = operation;
  8973. };
  8974. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8975. this._stencilState.stencilOpDepthFail = operation;
  8976. };
  8977. Engine.prototype.setStencilOperationPass = function (operation) {
  8978. this._stencilState.stencilOpStencilDepthPass = operation;
  8979. };
  8980. Engine.prototype.setDitheringState = function (value) {
  8981. if (value) {
  8982. this._gl.enable(this._gl.DITHER);
  8983. }
  8984. else {
  8985. this._gl.disable(this._gl.DITHER);
  8986. }
  8987. };
  8988. Engine.prototype.setRasterizerState = function (value) {
  8989. if (value) {
  8990. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  8991. }
  8992. else {
  8993. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  8994. }
  8995. };
  8996. /**
  8997. * stop executing a render loop function and remove it from the execution array
  8998. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8999. */
  9000. Engine.prototype.stopRenderLoop = function (renderFunction) {
  9001. if (!renderFunction) {
  9002. this._activeRenderLoops = [];
  9003. return;
  9004. }
  9005. var index = this._activeRenderLoops.indexOf(renderFunction);
  9006. if (index >= 0) {
  9007. this._activeRenderLoops.splice(index, 1);
  9008. }
  9009. };
  9010. Engine.prototype._renderLoop = function () {
  9011. if (!this._contextWasLost) {
  9012. var shouldRender = true;
  9013. if (!this.renderEvenInBackground && this._windowIsBackground) {
  9014. shouldRender = false;
  9015. }
  9016. if (shouldRender) {
  9017. // Start new frame
  9018. this.beginFrame();
  9019. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  9020. var renderFunction = this._activeRenderLoops[index];
  9021. renderFunction();
  9022. }
  9023. // Present
  9024. this.endFrame();
  9025. }
  9026. }
  9027. if (this._activeRenderLoops.length > 0) {
  9028. // Register new frame
  9029. var requester = null;
  9030. if (this._vrDisplay && this._vrDisplay.isPresenting)
  9031. requester = this._vrDisplay;
  9032. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  9033. }
  9034. else {
  9035. this._renderingQueueLaunched = false;
  9036. }
  9037. };
  9038. /**
  9039. * Register and execute a render loop. The engine can have more than one render function.
  9040. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  9041. * @example
  9042. * engine.runRenderLoop(function () {
  9043. * scene.render()
  9044. * })
  9045. */
  9046. Engine.prototype.runRenderLoop = function (renderFunction) {
  9047. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  9048. return;
  9049. }
  9050. this._activeRenderLoops.push(renderFunction);
  9051. if (!this._renderingQueueLaunched) {
  9052. this._renderingQueueLaunched = true;
  9053. this._bindedRenderFunction = this._renderLoop.bind(this);
  9054. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  9055. }
  9056. };
  9057. /**
  9058. * Toggle full screen mode.
  9059. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  9060. * @param {any} options - an options object to be sent to the requestFullscreen function
  9061. */
  9062. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  9063. if (this.isFullscreen) {
  9064. BABYLON.Tools.ExitFullscreen();
  9065. }
  9066. else {
  9067. this._pointerLockRequested = requestPointerLock;
  9068. if (this._renderingCanvas) {
  9069. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  9070. }
  9071. }
  9072. };
  9073. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  9074. if (stencil === void 0) { stencil = false; }
  9075. this.applyStates();
  9076. var mode = 0;
  9077. if (backBuffer && color) {
  9078. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  9079. mode |= this._gl.COLOR_BUFFER_BIT;
  9080. }
  9081. if (depth) {
  9082. this._gl.clearDepth(1.0);
  9083. mode |= this._gl.DEPTH_BUFFER_BIT;
  9084. }
  9085. if (stencil) {
  9086. this._gl.clearStencil(0);
  9087. mode |= this._gl.STENCIL_BUFFER_BIT;
  9088. }
  9089. this._gl.clear(mode);
  9090. };
  9091. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  9092. var gl = this._gl;
  9093. // Save state
  9094. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  9095. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  9096. // Change state
  9097. gl.enable(gl.SCISSOR_TEST);
  9098. gl.scissor(x, y, width, height);
  9099. // Clear
  9100. this.clear(clearColor, true, true, true);
  9101. // Restore state
  9102. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  9103. if (curScissor === true) {
  9104. gl.enable(gl.SCISSOR_TEST);
  9105. }
  9106. else {
  9107. gl.disable(gl.SCISSOR_TEST);
  9108. }
  9109. };
  9110. /**
  9111. * Set the WebGL's viewport
  9112. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  9113. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  9114. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  9115. */
  9116. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  9117. var width = requiredWidth || this.getRenderWidth();
  9118. var height = requiredHeight || this.getRenderHeight();
  9119. var x = viewport.x || 0;
  9120. var y = viewport.y || 0;
  9121. this._cachedViewport = viewport;
  9122. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  9123. };
  9124. /**
  9125. * Directly set the WebGL Viewport
  9126. * The x, y, width & height are directly passed to the WebGL call
  9127. * @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.
  9128. */
  9129. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  9130. var currentViewport = this._cachedViewport;
  9131. this._cachedViewport = null;
  9132. this._gl.viewport(x, y, width, height);
  9133. return currentViewport;
  9134. };
  9135. Engine.prototype.beginFrame = function () {
  9136. this.onBeginFrameObservable.notifyObservers(this);
  9137. this._measureFps();
  9138. };
  9139. Engine.prototype.endFrame = function () {
  9140. //force a flush in case we are using a bad OS.
  9141. if (this._badOS) {
  9142. this.flushFramebuffer();
  9143. }
  9144. //submit frame to the vr device, if enabled
  9145. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9146. // TODO: We should only submit the frame if we read frameData successfully.
  9147. this._vrDisplay.submitFrame();
  9148. }
  9149. this.onEndFrameObservable.notifyObservers(this);
  9150. };
  9151. /**
  9152. * resize the view according to the canvas' size.
  9153. * @example
  9154. * window.addEventListener("resize", function () {
  9155. * engine.resize();
  9156. * });
  9157. */
  9158. Engine.prototype.resize = function () {
  9159. // We're not resizing the size of the canvas while in VR mode & presenting
  9160. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  9161. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  9162. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  9163. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  9164. }
  9165. };
  9166. /**
  9167. * force a specific size of the canvas
  9168. * @param {number} width - the new canvas' width
  9169. * @param {number} height - the new canvas' height
  9170. */
  9171. Engine.prototype.setSize = function (width, height) {
  9172. if (!this._renderingCanvas) {
  9173. return;
  9174. }
  9175. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  9176. return;
  9177. }
  9178. this._renderingCanvas.width = width;
  9179. this._renderingCanvas.height = height;
  9180. for (var index = 0; index < this.scenes.length; index++) {
  9181. var scene = this.scenes[index];
  9182. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  9183. var cam = scene.cameras[camIndex];
  9184. cam._currentRenderId = 0;
  9185. }
  9186. }
  9187. if (this.onResizeObservable.hasObservers) {
  9188. this.onResizeObservable.notifyObservers(this);
  9189. }
  9190. };
  9191. // WebVR functions
  9192. Engine.prototype.isVRDevicePresent = function () {
  9193. return !!this._vrDisplay;
  9194. };
  9195. Engine.prototype.getVRDevice = function () {
  9196. return this._vrDisplay;
  9197. };
  9198. Engine.prototype.initWebVR = function () {
  9199. var _this = this;
  9200. var notifyObservers = function () {
  9201. var eventArgs = {
  9202. vrDisplay: _this._vrDisplay,
  9203. vrSupported: _this._vrSupported
  9204. };
  9205. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  9206. };
  9207. if (!this._onVrDisplayConnect) {
  9208. this._onVrDisplayConnect = function (event) {
  9209. _this._vrDisplay = event.display;
  9210. notifyObservers();
  9211. };
  9212. this._onVrDisplayDisconnect = function () {
  9213. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  9214. _this._vrDisplay = undefined;
  9215. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  9216. notifyObservers();
  9217. };
  9218. this._onVrDisplayPresentChange = function () {
  9219. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  9220. };
  9221. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  9222. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  9223. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  9224. }
  9225. this._getVRDisplays(notifyObservers);
  9226. return this.onVRDisplayChangedObservable;
  9227. };
  9228. Engine.prototype.enableVR = function () {
  9229. var _this = this;
  9230. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  9231. var onResolved = function () {
  9232. _this.onVRRequestPresentComplete.notifyObservers(true);
  9233. _this._onVRFullScreenTriggered();
  9234. };
  9235. var onRejected = function () {
  9236. _this.onVRRequestPresentComplete.notifyObservers(false);
  9237. };
  9238. this.onVRRequestPresentStart.notifyObservers(this);
  9239. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  9240. }
  9241. };
  9242. Engine.prototype.disableVR = function () {
  9243. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9244. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  9245. }
  9246. };
  9247. Engine.prototype._getVRDisplays = function (callback) {
  9248. var _this = this;
  9249. var getWebVRDevices = function (devices) {
  9250. _this._vrSupported = true;
  9251. // note that devices may actually be an empty array. This is fine;
  9252. // we expect this._vrDisplay to be undefined in this case.
  9253. return _this._vrDisplay = devices[0];
  9254. };
  9255. if (navigator.getVRDisplays) {
  9256. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  9257. // TODO: System CANNOT support WebVR, despite API presence.
  9258. _this._vrSupported = false;
  9259. callback();
  9260. });
  9261. }
  9262. else {
  9263. // TODO: Browser does not support WebVR
  9264. this._vrDisplay = undefined;
  9265. this._vrSupported = false;
  9266. callback();
  9267. }
  9268. };
  9269. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  9270. if (this._currentRenderTarget) {
  9271. this.unBindFramebuffer(this._currentRenderTarget);
  9272. }
  9273. this._currentRenderTarget = texture;
  9274. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  9275. var gl = this._gl;
  9276. if (texture.isCube) {
  9277. if (faceIndex === undefined) {
  9278. faceIndex = 0;
  9279. }
  9280. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  9281. }
  9282. if (this._cachedViewport && !forceFullscreenViewport) {
  9283. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  9284. }
  9285. else {
  9286. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  9287. }
  9288. this.wipeCaches();
  9289. };
  9290. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  9291. if (this._currentFramebuffer !== framebuffer) {
  9292. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  9293. this._currentFramebuffer = framebuffer;
  9294. }
  9295. };
  9296. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  9297. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  9298. this._currentRenderTarget = null;
  9299. // If MSAA, we need to bitblt back to main texture
  9300. var gl = this._gl;
  9301. if (texture._MSAAFramebuffer) {
  9302. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  9303. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  9304. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  9305. }
  9306. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  9307. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9308. gl.generateMipmap(gl.TEXTURE_2D);
  9309. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9310. }
  9311. if (onBeforeUnbind) {
  9312. if (texture._MSAAFramebuffer) {
  9313. // Bind the correct framebuffer
  9314. this.bindUnboundFramebuffer(texture._framebuffer);
  9315. }
  9316. onBeforeUnbind();
  9317. }
  9318. this.bindUnboundFramebuffer(null);
  9319. };
  9320. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  9321. if (texture.generateMipMaps) {
  9322. var gl = this._gl;
  9323. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9324. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9325. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9326. }
  9327. };
  9328. Engine.prototype.flushFramebuffer = function () {
  9329. this._gl.flush();
  9330. };
  9331. Engine.prototype.restoreDefaultFramebuffer = function () {
  9332. if (this._currentRenderTarget) {
  9333. this.unBindFramebuffer(this._currentRenderTarget);
  9334. }
  9335. else {
  9336. this.bindUnboundFramebuffer(null);
  9337. }
  9338. if (this._cachedViewport) {
  9339. this.setViewport(this._cachedViewport);
  9340. }
  9341. this.wipeCaches();
  9342. };
  9343. // UBOs
  9344. Engine.prototype.createUniformBuffer = function (elements) {
  9345. var ubo = this._gl.createBuffer();
  9346. if (!ubo) {
  9347. throw new Error("Unable to create uniform buffer");
  9348. }
  9349. this.bindUniformBuffer(ubo);
  9350. if (elements instanceof Float32Array) {
  9351. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  9352. }
  9353. else {
  9354. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  9355. }
  9356. this.bindUniformBuffer(null);
  9357. ubo.references = 1;
  9358. return ubo;
  9359. };
  9360. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  9361. var ubo = this._gl.createBuffer();
  9362. if (!ubo) {
  9363. throw new Error("Unable to create dynamic uniform buffer");
  9364. }
  9365. this.bindUniformBuffer(ubo);
  9366. if (elements instanceof Float32Array) {
  9367. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  9368. }
  9369. else {
  9370. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  9371. }
  9372. this.bindUniformBuffer(null);
  9373. ubo.references = 1;
  9374. return ubo;
  9375. };
  9376. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  9377. this.bindUniformBuffer(uniformBuffer);
  9378. if (offset === undefined) {
  9379. offset = 0;
  9380. }
  9381. if (count === undefined) {
  9382. if (elements instanceof Float32Array) {
  9383. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  9384. }
  9385. else {
  9386. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  9387. }
  9388. }
  9389. else {
  9390. if (elements instanceof Float32Array) {
  9391. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  9392. }
  9393. else {
  9394. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  9395. }
  9396. }
  9397. this.bindUniformBuffer(null);
  9398. };
  9399. // VBOs
  9400. Engine.prototype._resetVertexBufferBinding = function () {
  9401. this.bindArrayBuffer(null);
  9402. this._cachedVertexBuffers = null;
  9403. };
  9404. Engine.prototype.createVertexBuffer = function (vertices) {
  9405. var vbo = this._gl.createBuffer();
  9406. if (!vbo) {
  9407. throw new Error("Unable to create vertex buffer");
  9408. }
  9409. this.bindArrayBuffer(vbo);
  9410. if (vertices instanceof Float32Array) {
  9411. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  9412. }
  9413. else {
  9414. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  9415. }
  9416. this._resetVertexBufferBinding();
  9417. vbo.references = 1;
  9418. return vbo;
  9419. };
  9420. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9421. var vbo = this._gl.createBuffer();
  9422. if (!vbo) {
  9423. throw new Error("Unable to create dynamic vertex buffer");
  9424. }
  9425. this.bindArrayBuffer(vbo);
  9426. if (vertices instanceof Float32Array) {
  9427. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9428. }
  9429. else {
  9430. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9431. }
  9432. this._resetVertexBufferBinding();
  9433. vbo.references = 1;
  9434. return vbo;
  9435. };
  9436. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  9437. if (offset === void 0) { offset = 0; }
  9438. // Force cache update
  9439. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  9440. this.bindIndexBuffer(indexBuffer);
  9441. var arrayBuffer;
  9442. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  9443. arrayBuffer = indices;
  9444. }
  9445. else {
  9446. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9447. }
  9448. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  9449. this._resetIndexBufferBinding();
  9450. };
  9451. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9452. this.bindArrayBuffer(vertexBuffer);
  9453. if (offset === undefined) {
  9454. offset = 0;
  9455. }
  9456. if (count === undefined) {
  9457. if (vertices instanceof Float32Array) {
  9458. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9459. }
  9460. else {
  9461. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9462. }
  9463. }
  9464. else {
  9465. if (vertices instanceof Float32Array) {
  9466. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9467. }
  9468. else {
  9469. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9470. }
  9471. }
  9472. this._resetVertexBufferBinding();
  9473. };
  9474. Engine.prototype._resetIndexBufferBinding = function () {
  9475. this.bindIndexBuffer(null);
  9476. this._cachedIndexBuffer = null;
  9477. };
  9478. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  9479. var vbo = this._gl.createBuffer();
  9480. if (!vbo) {
  9481. throw new Error("Unable to create index buffer");
  9482. }
  9483. this.bindIndexBuffer(vbo);
  9484. // Check for 32 bits indices
  9485. var arrayBuffer;
  9486. var need32Bits = false;
  9487. if (indices instanceof Uint16Array) {
  9488. arrayBuffer = indices;
  9489. }
  9490. else {
  9491. //check 32 bit support
  9492. if (this._caps.uintIndices) {
  9493. if (indices instanceof Uint32Array) {
  9494. arrayBuffer = indices;
  9495. need32Bits = true;
  9496. }
  9497. else {
  9498. //number[] or Int32Array, check if 32 bit is necessary
  9499. for (var index = 0; index < indices.length; index++) {
  9500. if (indices[index] > 65535) {
  9501. need32Bits = true;
  9502. break;
  9503. }
  9504. }
  9505. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9506. }
  9507. }
  9508. else {
  9509. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9510. arrayBuffer = new Uint16Array(indices);
  9511. }
  9512. }
  9513. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  9514. this._resetIndexBufferBinding();
  9515. vbo.references = 1;
  9516. vbo.is32Bits = need32Bits;
  9517. return vbo;
  9518. };
  9519. Engine.prototype.bindArrayBuffer = function (buffer) {
  9520. if (!this._vaoRecordInProgress) {
  9521. this._unbindVertexArrayObject();
  9522. }
  9523. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9524. };
  9525. Engine.prototype.bindUniformBuffer = function (buffer) {
  9526. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9527. };
  9528. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9529. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9530. };
  9531. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9532. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9533. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9534. };
  9535. ;
  9536. Engine.prototype.bindIndexBuffer = function (buffer) {
  9537. if (!this._vaoRecordInProgress) {
  9538. this._unbindVertexArrayObject();
  9539. }
  9540. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9541. };
  9542. Engine.prototype.bindBuffer = function (buffer, target) {
  9543. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9544. this._gl.bindBuffer(target, buffer);
  9545. this._currentBoundBuffer[target] = buffer;
  9546. }
  9547. };
  9548. Engine.prototype.updateArrayBuffer = function (data) {
  9549. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9550. };
  9551. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9552. var pointer = this._currentBufferPointers[indx];
  9553. var changed = false;
  9554. if (!pointer.active) {
  9555. changed = true;
  9556. pointer.active = true;
  9557. pointer.index = indx;
  9558. pointer.size = size;
  9559. pointer.type = type;
  9560. pointer.normalized = normalized;
  9561. pointer.stride = stride;
  9562. pointer.offset = offset;
  9563. pointer.buffer = buffer;
  9564. }
  9565. else {
  9566. if (pointer.buffer !== buffer) {
  9567. pointer.buffer = buffer;
  9568. changed = true;
  9569. }
  9570. if (pointer.size !== size) {
  9571. pointer.size = size;
  9572. changed = true;
  9573. }
  9574. if (pointer.type !== type) {
  9575. pointer.type = type;
  9576. changed = true;
  9577. }
  9578. if (pointer.normalized !== normalized) {
  9579. pointer.normalized = normalized;
  9580. changed = true;
  9581. }
  9582. if (pointer.stride !== stride) {
  9583. pointer.stride = stride;
  9584. changed = true;
  9585. }
  9586. if (pointer.offset !== offset) {
  9587. pointer.offset = offset;
  9588. changed = true;
  9589. }
  9590. }
  9591. if (changed || this._vaoRecordInProgress) {
  9592. this.bindArrayBuffer(buffer);
  9593. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9594. }
  9595. };
  9596. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9597. if (indexBuffer == null) {
  9598. return;
  9599. }
  9600. if (this._cachedIndexBuffer !== indexBuffer) {
  9601. this._cachedIndexBuffer = indexBuffer;
  9602. this.bindIndexBuffer(indexBuffer);
  9603. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9604. }
  9605. };
  9606. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9607. var attributes = effect.getAttributesNames();
  9608. if (!this._vaoRecordInProgress) {
  9609. this._unbindVertexArrayObject();
  9610. }
  9611. this.unbindAllAttributes();
  9612. for (var index = 0; index < attributes.length; index++) {
  9613. var order = effect.getAttributeLocation(index);
  9614. if (order >= 0) {
  9615. var vertexBuffer = vertexBuffers[attributes[index]];
  9616. if (!vertexBuffer) {
  9617. continue;
  9618. }
  9619. this._gl.enableVertexAttribArray(order);
  9620. if (!this._vaoRecordInProgress) {
  9621. this._vertexAttribArraysEnabled[order] = true;
  9622. }
  9623. var buffer = vertexBuffer.getBuffer();
  9624. if (buffer) {
  9625. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9626. if (vertexBuffer.getIsInstanced()) {
  9627. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9628. if (!this._vaoRecordInProgress) {
  9629. this._currentInstanceLocations.push(order);
  9630. this._currentInstanceBuffers.push(buffer);
  9631. }
  9632. }
  9633. }
  9634. }
  9635. }
  9636. };
  9637. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9638. var vao = this._gl.createVertexArray();
  9639. this._vaoRecordInProgress = true;
  9640. this._gl.bindVertexArray(vao);
  9641. this._mustWipeVertexAttributes = true;
  9642. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9643. this.bindIndexBuffer(indexBuffer);
  9644. this._vaoRecordInProgress = false;
  9645. this._gl.bindVertexArray(null);
  9646. return vao;
  9647. };
  9648. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9649. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9650. this._cachedVertexArrayObject = vertexArrayObject;
  9651. this._gl.bindVertexArray(vertexArrayObject);
  9652. this._cachedVertexBuffers = null;
  9653. this._cachedIndexBuffer = null;
  9654. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9655. this._mustWipeVertexAttributes = true;
  9656. }
  9657. };
  9658. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9659. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9660. this._cachedVertexBuffers = vertexBuffer;
  9661. this._cachedEffectForVertexBuffers = effect;
  9662. var attributesCount = effect.getAttributesCount();
  9663. this._unbindVertexArrayObject();
  9664. this.unbindAllAttributes();
  9665. var offset = 0;
  9666. for (var index = 0; index < attributesCount; index++) {
  9667. if (index < vertexDeclaration.length) {
  9668. var order = effect.getAttributeLocation(index);
  9669. if (order >= 0) {
  9670. this._gl.enableVertexAttribArray(order);
  9671. this._vertexAttribArraysEnabled[order] = true;
  9672. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9673. }
  9674. offset += vertexDeclaration[index] * 4;
  9675. }
  9676. }
  9677. }
  9678. this._bindIndexBufferWithCache(indexBuffer);
  9679. };
  9680. Engine.prototype._unbindVertexArrayObject = function () {
  9681. if (!this._cachedVertexArrayObject) {
  9682. return;
  9683. }
  9684. this._cachedVertexArrayObject = null;
  9685. this._gl.bindVertexArray(null);
  9686. };
  9687. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9688. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9689. this._cachedVertexBuffers = vertexBuffers;
  9690. this._cachedEffectForVertexBuffers = effect;
  9691. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9692. }
  9693. this._bindIndexBufferWithCache(indexBuffer);
  9694. };
  9695. Engine.prototype.unbindInstanceAttributes = function () {
  9696. var boundBuffer;
  9697. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9698. var instancesBuffer = this._currentInstanceBuffers[i];
  9699. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9700. boundBuffer = instancesBuffer;
  9701. this.bindArrayBuffer(instancesBuffer);
  9702. }
  9703. var offsetLocation = this._currentInstanceLocations[i];
  9704. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9705. }
  9706. this._currentInstanceBuffers.length = 0;
  9707. this._currentInstanceLocations.length = 0;
  9708. };
  9709. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9710. this._gl.deleteVertexArray(vao);
  9711. };
  9712. Engine.prototype._releaseBuffer = function (buffer) {
  9713. buffer.references--;
  9714. if (buffer.references === 0) {
  9715. this._gl.deleteBuffer(buffer);
  9716. return true;
  9717. }
  9718. return false;
  9719. };
  9720. Engine.prototype.createInstancesBuffer = function (capacity) {
  9721. var buffer = this._gl.createBuffer();
  9722. if (!buffer) {
  9723. throw new Error("Unable to create instance buffer");
  9724. }
  9725. buffer.capacity = capacity;
  9726. this.bindArrayBuffer(buffer);
  9727. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9728. return buffer;
  9729. };
  9730. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9731. this._gl.deleteBuffer(buffer);
  9732. };
  9733. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9734. this.bindArrayBuffer(instancesBuffer);
  9735. if (data) {
  9736. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9737. }
  9738. if (offsetLocations[0].index !== undefined) {
  9739. var stride = 0;
  9740. for (var i = 0; i < offsetLocations.length; i++) {
  9741. var ai = offsetLocations[i];
  9742. stride += ai.attributeSize * 4;
  9743. }
  9744. for (var i = 0; i < offsetLocations.length; i++) {
  9745. var ai = offsetLocations[i];
  9746. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9747. this._gl.enableVertexAttribArray(ai.index);
  9748. this._vertexAttribArraysEnabled[ai.index] = true;
  9749. }
  9750. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9751. this._gl.vertexAttribDivisor(ai.index, 1);
  9752. this._currentInstanceLocations.push(ai.index);
  9753. this._currentInstanceBuffers.push(instancesBuffer);
  9754. }
  9755. }
  9756. else {
  9757. for (var index = 0; index < 4; index++) {
  9758. var offsetLocation = offsetLocations[index];
  9759. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9760. this._gl.enableVertexAttribArray(offsetLocation);
  9761. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9762. }
  9763. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9764. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9765. this._currentInstanceLocations.push(offsetLocation);
  9766. this._currentInstanceBuffers.push(instancesBuffer);
  9767. }
  9768. }
  9769. };
  9770. Engine.prototype.applyStates = function () {
  9771. this._depthCullingState.apply(this._gl);
  9772. this._stencilState.apply(this._gl);
  9773. this._alphaState.apply(this._gl);
  9774. };
  9775. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9776. // Apply states
  9777. this.applyStates();
  9778. this._drawCalls.addCount(1, false);
  9779. // Render
  9780. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9781. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9782. if (instancesCount) {
  9783. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9784. return;
  9785. }
  9786. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9787. };
  9788. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9789. // Apply states
  9790. this.applyStates();
  9791. this._drawCalls.addCount(1, false);
  9792. if (instancesCount) {
  9793. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9794. return;
  9795. }
  9796. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9797. };
  9798. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9799. // Apply states
  9800. this.applyStates();
  9801. this._drawCalls.addCount(1, false);
  9802. if (instancesCount) {
  9803. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9804. return;
  9805. }
  9806. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9807. };
  9808. // Shaders
  9809. Engine.prototype._releaseEffect = function (effect) {
  9810. if (this._compiledEffects[effect._key]) {
  9811. delete this._compiledEffects[effect._key];
  9812. this._deleteProgram(effect.getProgram());
  9813. }
  9814. };
  9815. Engine.prototype._deleteProgram = function (program) {
  9816. if (program) {
  9817. program.__SPECTOR_rebuildProgram = null;
  9818. if (program.transformFeedback) {
  9819. this.deleteTransformFeedback(program.transformFeedback);
  9820. program.transformFeedback = null;
  9821. }
  9822. this._gl.deleteProgram(program);
  9823. }
  9824. };
  9825. /**
  9826. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9827. * @param samplers An array of string used to represent textures
  9828. */
  9829. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9830. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9831. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9832. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9833. if (this._compiledEffects[name]) {
  9834. var compiledEffect = this._compiledEffects[name];
  9835. if (onCompiled && compiledEffect.isReady()) {
  9836. onCompiled(compiledEffect);
  9837. }
  9838. return compiledEffect;
  9839. }
  9840. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9841. effect._key = name;
  9842. this._compiledEffects[name] = effect;
  9843. return effect;
  9844. };
  9845. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9846. if (uniformsNames === void 0) { uniformsNames = []; }
  9847. if (samplers === void 0) { samplers = []; }
  9848. if (defines === void 0) { defines = ""; }
  9849. return this.createEffect({
  9850. vertex: "particles",
  9851. fragmentElement: fragmentName
  9852. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9853. };
  9854. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  9855. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9856. context = context || this._gl;
  9857. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  9858. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  9859. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  9860. };
  9861. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  9862. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9863. context = context || this._gl;
  9864. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  9865. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9866. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9867. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9868. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  9869. this.onAfterShaderCompilationObservable.notifyObservers(this);
  9870. return program;
  9871. };
  9872. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  9873. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9874. var shaderProgram = context.createProgram();
  9875. if (!shaderProgram) {
  9876. throw new Error("Unable to create program");
  9877. }
  9878. context.attachShader(shaderProgram, vertexShader);
  9879. context.attachShader(shaderProgram, fragmentShader);
  9880. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  9881. var transformFeedback = this.createTransformFeedback();
  9882. this.bindTransformFeedback(transformFeedback);
  9883. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  9884. shaderProgram.transformFeedback = transformFeedback;
  9885. }
  9886. context.linkProgram(shaderProgram);
  9887. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  9888. this.bindTransformFeedback(null);
  9889. }
  9890. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9891. if (!linked) {
  9892. context.validateProgram(shaderProgram);
  9893. var error = context.getProgramInfoLog(shaderProgram);
  9894. if (error) {
  9895. throw new Error(error);
  9896. }
  9897. }
  9898. context.deleteShader(vertexShader);
  9899. context.deleteShader(fragmentShader);
  9900. return shaderProgram;
  9901. };
  9902. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9903. var results = new Array();
  9904. for (var index = 0; index < uniformsNames.length; index++) {
  9905. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9906. }
  9907. return results;
  9908. };
  9909. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9910. var results = [];
  9911. for (var index = 0; index < attributesNames.length; index++) {
  9912. try {
  9913. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9914. }
  9915. catch (e) {
  9916. results.push(-1);
  9917. }
  9918. }
  9919. return results;
  9920. };
  9921. Engine.prototype.enableEffect = function (effect) {
  9922. if (!effect) {
  9923. return;
  9924. }
  9925. // Use program
  9926. this.setProgram(effect.getProgram());
  9927. this._currentEffect = effect;
  9928. if (effect.onBind) {
  9929. effect.onBind(effect);
  9930. }
  9931. effect.onBindObservable.notifyObservers(effect);
  9932. };
  9933. Engine.prototype.setIntArray = function (uniform, array) {
  9934. if (!uniform)
  9935. return;
  9936. this._gl.uniform1iv(uniform, array);
  9937. };
  9938. Engine.prototype.setIntArray2 = function (uniform, array) {
  9939. if (!uniform || array.length % 2 !== 0)
  9940. return;
  9941. this._gl.uniform2iv(uniform, array);
  9942. };
  9943. Engine.prototype.setIntArray3 = function (uniform, array) {
  9944. if (!uniform || array.length % 3 !== 0)
  9945. return;
  9946. this._gl.uniform3iv(uniform, array);
  9947. };
  9948. Engine.prototype.setIntArray4 = function (uniform, array) {
  9949. if (!uniform || array.length % 4 !== 0)
  9950. return;
  9951. this._gl.uniform4iv(uniform, array);
  9952. };
  9953. Engine.prototype.setFloatArray = function (uniform, array) {
  9954. if (!uniform)
  9955. return;
  9956. this._gl.uniform1fv(uniform, array);
  9957. };
  9958. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9959. if (!uniform || array.length % 2 !== 0)
  9960. return;
  9961. this._gl.uniform2fv(uniform, array);
  9962. };
  9963. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9964. if (!uniform || array.length % 3 !== 0)
  9965. return;
  9966. this._gl.uniform3fv(uniform, array);
  9967. };
  9968. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9969. if (!uniform || array.length % 4 !== 0)
  9970. return;
  9971. this._gl.uniform4fv(uniform, array);
  9972. };
  9973. Engine.prototype.setArray = function (uniform, array) {
  9974. if (!uniform)
  9975. return;
  9976. this._gl.uniform1fv(uniform, array);
  9977. };
  9978. Engine.prototype.setArray2 = function (uniform, array) {
  9979. if (!uniform || array.length % 2 !== 0)
  9980. return;
  9981. this._gl.uniform2fv(uniform, array);
  9982. };
  9983. Engine.prototype.setArray3 = function (uniform, array) {
  9984. if (!uniform || array.length % 3 !== 0)
  9985. return;
  9986. this._gl.uniform3fv(uniform, array);
  9987. };
  9988. Engine.prototype.setArray4 = function (uniform, array) {
  9989. if (!uniform || array.length % 4 !== 0)
  9990. return;
  9991. this._gl.uniform4fv(uniform, array);
  9992. };
  9993. Engine.prototype.setMatrices = function (uniform, matrices) {
  9994. if (!uniform)
  9995. return;
  9996. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9997. };
  9998. Engine.prototype.setMatrix = function (uniform, matrix) {
  9999. if (!uniform)
  10000. return;
  10001. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  10002. };
  10003. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  10004. if (!uniform)
  10005. return;
  10006. this._gl.uniformMatrix3fv(uniform, false, matrix);
  10007. };
  10008. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  10009. if (!uniform)
  10010. return;
  10011. this._gl.uniformMatrix2fv(uniform, false, matrix);
  10012. };
  10013. Engine.prototype.setFloat = function (uniform, value) {
  10014. if (!uniform)
  10015. return;
  10016. this._gl.uniform1f(uniform, value);
  10017. };
  10018. Engine.prototype.setFloat2 = function (uniform, x, y) {
  10019. if (!uniform)
  10020. return;
  10021. this._gl.uniform2f(uniform, x, y);
  10022. };
  10023. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  10024. if (!uniform)
  10025. return;
  10026. this._gl.uniform3f(uniform, x, y, z);
  10027. };
  10028. Engine.prototype.setBool = function (uniform, bool) {
  10029. if (!uniform)
  10030. return;
  10031. this._gl.uniform1i(uniform, bool);
  10032. };
  10033. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  10034. if (!uniform)
  10035. return;
  10036. this._gl.uniform4f(uniform, x, y, z, w);
  10037. };
  10038. Engine.prototype.setColor3 = function (uniform, color3) {
  10039. if (!uniform)
  10040. return;
  10041. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  10042. };
  10043. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  10044. if (!uniform)
  10045. return;
  10046. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  10047. };
  10048. // States
  10049. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  10050. if (zOffset === void 0) { zOffset = 0; }
  10051. if (reverseSide === void 0) { reverseSide = false; }
  10052. // Culling
  10053. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  10054. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  10055. var cullFace = this.cullBackFaces ? showSide : hideSide;
  10056. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  10057. if (culling) {
  10058. this._depthCullingState.cullFace = cullFace;
  10059. this._depthCullingState.cull = true;
  10060. }
  10061. else {
  10062. this._depthCullingState.cull = false;
  10063. }
  10064. }
  10065. // Z offset
  10066. this.setZOffset(zOffset);
  10067. };
  10068. Engine.prototype.setZOffset = function (value) {
  10069. this._depthCullingState.zOffset = value;
  10070. };
  10071. Engine.prototype.getZOffset = function () {
  10072. return this._depthCullingState.zOffset;
  10073. };
  10074. Engine.prototype.setDepthBuffer = function (enable) {
  10075. this._depthCullingState.depthTest = enable;
  10076. };
  10077. Engine.prototype.getDepthWrite = function () {
  10078. return this._depthCullingState.depthMask;
  10079. };
  10080. Engine.prototype.setDepthWrite = function (enable) {
  10081. this._depthCullingState.depthMask = enable;
  10082. };
  10083. Engine.prototype.setColorWrite = function (enable) {
  10084. this._gl.colorMask(enable, enable, enable, enable);
  10085. this._colorWrite = enable;
  10086. };
  10087. Engine.prototype.getColorWrite = function () {
  10088. return this._colorWrite;
  10089. };
  10090. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  10091. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  10092. };
  10093. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  10094. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  10095. if (this._alphaMode === mode) {
  10096. return;
  10097. }
  10098. switch (mode) {
  10099. case Engine.ALPHA_DISABLE:
  10100. this._alphaState.alphaBlend = false;
  10101. break;
  10102. case Engine.ALPHA_PREMULTIPLIED:
  10103. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10104. this._alphaState.alphaBlend = true;
  10105. break;
  10106. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  10107. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10108. this._alphaState.alphaBlend = true;
  10109. break;
  10110. case Engine.ALPHA_COMBINE:
  10111. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10112. this._alphaState.alphaBlend = true;
  10113. break;
  10114. case Engine.ALPHA_ONEONE:
  10115. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10116. this._alphaState.alphaBlend = true;
  10117. break;
  10118. case Engine.ALPHA_ADD:
  10119. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10120. this._alphaState.alphaBlend = true;
  10121. break;
  10122. case Engine.ALPHA_SUBTRACT:
  10123. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10124. this._alphaState.alphaBlend = true;
  10125. break;
  10126. case Engine.ALPHA_MULTIPLY:
  10127. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  10128. this._alphaState.alphaBlend = true;
  10129. break;
  10130. case Engine.ALPHA_MAXIMIZED:
  10131. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10132. this._alphaState.alphaBlend = true;
  10133. break;
  10134. case Engine.ALPHA_INTERPOLATE:
  10135. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  10136. this._alphaState.alphaBlend = true;
  10137. break;
  10138. case Engine.ALPHA_SCREENMODE:
  10139. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10140. this._alphaState.alphaBlend = true;
  10141. break;
  10142. }
  10143. if (!noDepthWriteChange) {
  10144. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  10145. }
  10146. this._alphaMode = mode;
  10147. };
  10148. Engine.prototype.getAlphaMode = function () {
  10149. return this._alphaMode;
  10150. };
  10151. Engine.prototype.setAlphaTesting = function (enable) {
  10152. this._alphaTest = enable;
  10153. };
  10154. Engine.prototype.getAlphaTesting = function () {
  10155. return !!this._alphaTest;
  10156. };
  10157. // Textures
  10158. Engine.prototype.wipeCaches = function (bruteForce) {
  10159. if (this.preventCacheWipeBetweenFrames) {
  10160. return;
  10161. }
  10162. this.resetTextureCache();
  10163. this._currentEffect = null;
  10164. // 6/8/2017: deltakosh: Should not be required anymore.
  10165. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  10166. if (bruteForce) {
  10167. this._currentProgram = null;
  10168. this._stencilState.reset();
  10169. this._depthCullingState.reset();
  10170. this.setDepthFunctionToLessOrEqual();
  10171. this._alphaState.reset();
  10172. }
  10173. this._cachedVertexBuffers = null;
  10174. this._cachedIndexBuffer = null;
  10175. this._cachedEffectForVertexBuffers = null;
  10176. this._unbindVertexArrayObject();
  10177. this.bindIndexBuffer(null);
  10178. this.bindArrayBuffer(null);
  10179. };
  10180. /**
  10181. * Set the compressed texture format to use, based on the formats you have, and the formats
  10182. * supported by the hardware / browser.
  10183. *
  10184. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  10185. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  10186. * to API arguments needed to compressed textures. This puts the burden on the container
  10187. * generator to house the arcane code for determining these for current & future formats.
  10188. *
  10189. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  10190. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  10191. *
  10192. * Note: The result of this call is not taken into account when a texture is base64.
  10193. *
  10194. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  10195. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  10196. *
  10197. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  10198. * @returns The extension selected.
  10199. */
  10200. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  10201. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  10202. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  10203. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  10204. return this._textureFormatInUse = this._texturesSupported[i];
  10205. }
  10206. }
  10207. }
  10208. // actively set format to nothing, to allow this to be called more than once
  10209. // and possibly fail the 2nd time
  10210. this._textureFormatInUse = null;
  10211. return null;
  10212. };
  10213. Engine.prototype._createTexture = function () {
  10214. var texture = this._gl.createTexture();
  10215. if (!texture) {
  10216. throw new Error("Unable to create texture");
  10217. }
  10218. return texture;
  10219. };
  10220. /**
  10221. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  10222. * @param {string} urlArg- This contains one of the following:
  10223. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  10224. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  10225. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  10226. *
  10227. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  10228. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  10229. * @param {Scene} scene- Needed for loading to the correct scene.
  10230. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  10231. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  10232. * @param {callback} onError- Optional callback to be called upon failure.
  10233. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  10234. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  10235. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  10236. *
  10237. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  10238. */
  10239. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  10240. var _this = this;
  10241. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10242. if (onLoad === void 0) { onLoad = null; }
  10243. if (onError === void 0) { onError = null; }
  10244. if (buffer === void 0) { buffer = null; }
  10245. if (fallBack === void 0) { fallBack = null; }
  10246. if (format === void 0) { format = null; }
  10247. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  10248. var fromData = url.substr(0, 5) === "data:";
  10249. var fromBlob = url.substr(0, 5) === "blob:";
  10250. var isBase64 = fromData && url.indexOf("base64") !== -1;
  10251. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  10252. // establish the file extension, if possible
  10253. var lastDot = url.lastIndexOf('.');
  10254. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  10255. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10256. var isTGA = (extension === ".tga");
  10257. // determine if a ktx file should be substituted
  10258. var isKTX = false;
  10259. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  10260. url = url.substring(0, lastDot) + this._textureFormatInUse;
  10261. isKTX = true;
  10262. }
  10263. if (scene) {
  10264. scene._addPendingData(texture);
  10265. }
  10266. texture.url = url;
  10267. texture.generateMipMaps = !noMipmap;
  10268. texture.samplingMode = samplingMode;
  10269. texture.invertY = invertY;
  10270. if (!this._doNotHandleContextLost) {
  10271. // Keep a link to the buffer only if we plan to handle context lost
  10272. texture._buffer = buffer;
  10273. }
  10274. var onLoadObserver = null;
  10275. if (onLoad && !fallBack) {
  10276. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  10277. }
  10278. if (!fallBack)
  10279. this._internalTexturesCache.push(texture);
  10280. var onerror = function () {
  10281. if (scene) {
  10282. scene._removePendingData(texture);
  10283. }
  10284. if (onLoadObserver) {
  10285. texture.onLoadedObservable.remove(onLoadObserver);
  10286. }
  10287. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  10288. if (isKTX) {
  10289. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10290. }
  10291. else if (BABYLON.Tools.UseFallbackTexture) {
  10292. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10293. }
  10294. if (onError) {
  10295. onError();
  10296. }
  10297. };
  10298. var callback = null;
  10299. // processing for non-image formats
  10300. if (isKTX || isTGA || isDDS) {
  10301. if (isKTX) {
  10302. callback = function (data) {
  10303. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  10304. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  10305. ktx.uploadLevels(_this._gl, !noMipmap);
  10306. return false;
  10307. }, samplingMode);
  10308. };
  10309. }
  10310. else if (isTGA) {
  10311. callback = function (arrayBuffer) {
  10312. var data = new Uint8Array(arrayBuffer);
  10313. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  10314. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  10315. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  10316. return false;
  10317. }, samplingMode);
  10318. };
  10319. }
  10320. else if (isDDS) {
  10321. callback = function (data) {
  10322. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10323. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  10324. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  10325. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  10326. return false;
  10327. }, samplingMode);
  10328. };
  10329. }
  10330. if (!buffer) {
  10331. BABYLON.Tools.LoadFile(url, function (data) {
  10332. if (callback) {
  10333. callback(data);
  10334. }
  10335. }, undefined, scene ? scene.database : undefined, true, onerror);
  10336. }
  10337. else {
  10338. if (callback) {
  10339. callback(buffer);
  10340. }
  10341. }
  10342. // image format processing
  10343. }
  10344. else {
  10345. var onload = function (img) {
  10346. if (fromBlob && !_this._doNotHandleContextLost) {
  10347. // We need to store the image if we need to rebuild the texture
  10348. // in case of a webgl context lost
  10349. texture._buffer = img;
  10350. }
  10351. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  10352. var gl = _this._gl;
  10353. var isPot = (img.width === potWidth && img.height === potHeight);
  10354. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  10355. if (isPot) {
  10356. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10357. return false;
  10358. }
  10359. // Using shaders to rescale because canvas.drawImage is lossy
  10360. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10361. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  10362. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10363. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10364. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10365. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10366. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10367. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  10368. _this._releaseTexture(source);
  10369. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10370. continuationCallback();
  10371. });
  10372. return true;
  10373. }, samplingMode);
  10374. };
  10375. if (!fromData || isBase64)
  10376. if (buffer instanceof HTMLImageElement) {
  10377. onload(buffer);
  10378. }
  10379. else {
  10380. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10381. }
  10382. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  10383. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  10384. else
  10385. onload(buffer);
  10386. }
  10387. return texture;
  10388. };
  10389. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  10390. var _this = this;
  10391. var rtt = this.createRenderTargetTexture({
  10392. width: destination.width,
  10393. height: destination.height,
  10394. }, {
  10395. generateMipMaps: false,
  10396. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  10397. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  10398. generateDepthBuffer: false,
  10399. generateStencilBuffer: false
  10400. });
  10401. if (!this._rescalePostProcess) {
  10402. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  10403. }
  10404. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  10405. _this._rescalePostProcess.onApply = function (effect) {
  10406. effect._bindTexture("textureSampler", source);
  10407. };
  10408. var hostingScene = scene;
  10409. if (!hostingScene) {
  10410. hostingScene = _this.scenes[_this.scenes.length - 1];
  10411. }
  10412. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  10413. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  10414. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  10415. _this.unBindFramebuffer(rtt);
  10416. _this._releaseTexture(rtt);
  10417. if (onComplete) {
  10418. onComplete();
  10419. }
  10420. });
  10421. };
  10422. Engine.prototype._getInternalFormat = function (format) {
  10423. var internalFormat = this._gl.RGBA;
  10424. switch (format) {
  10425. case Engine.TEXTUREFORMAT_ALPHA:
  10426. internalFormat = this._gl.ALPHA;
  10427. break;
  10428. case Engine.TEXTUREFORMAT_LUMINANCE:
  10429. internalFormat = this._gl.LUMINANCE;
  10430. break;
  10431. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  10432. internalFormat = this._gl.LUMINANCE_ALPHA;
  10433. break;
  10434. case Engine.TEXTUREFORMAT_RGB:
  10435. internalFormat = this._gl.RGB;
  10436. break;
  10437. case Engine.TEXTUREFORMAT_RGBA:
  10438. internalFormat = this._gl.RGBA;
  10439. break;
  10440. }
  10441. return internalFormat;
  10442. };
  10443. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  10444. if (compression === void 0) { compression = null; }
  10445. if (!texture) {
  10446. return;
  10447. }
  10448. var internalFormat = this._getInternalFormat(format);
  10449. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10450. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10451. if (!this._doNotHandleContextLost) {
  10452. texture._bufferView = data;
  10453. texture.format = format;
  10454. texture.invertY = invertY;
  10455. texture._compression = compression;
  10456. }
  10457. if (texture.width % 4 !== 0) {
  10458. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  10459. }
  10460. if (compression && data) {
  10461. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  10462. }
  10463. else {
  10464. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  10465. }
  10466. if (texture.generateMipMaps) {
  10467. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10468. }
  10469. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10470. this.resetTextureCache();
  10471. texture.isReady = true;
  10472. };
  10473. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  10474. if (compression === void 0) { compression = null; }
  10475. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  10476. texture.baseWidth = width;
  10477. texture.baseHeight = height;
  10478. texture.width = width;
  10479. texture.height = height;
  10480. texture.format = format;
  10481. texture.generateMipMaps = generateMipMaps;
  10482. texture.samplingMode = samplingMode;
  10483. texture.invertY = invertY;
  10484. texture._compression = compression;
  10485. if (!this._doNotHandleContextLost) {
  10486. texture._bufferView = data;
  10487. }
  10488. this.updateRawTexture(texture, data, format, invertY, compression);
  10489. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10490. // Filters
  10491. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  10492. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10493. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10494. if (generateMipMaps) {
  10495. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10496. }
  10497. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10498. this._internalTexturesCache.push(texture);
  10499. return texture;
  10500. };
  10501. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  10502. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  10503. texture.baseWidth = width;
  10504. texture.baseHeight = height;
  10505. if (generateMipMaps) {
  10506. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  10507. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  10508. }
  10509. this.resetTextureCache();
  10510. texture.width = width;
  10511. texture.height = height;
  10512. texture.isReady = false;
  10513. texture.generateMipMaps = generateMipMaps;
  10514. texture.samplingMode = samplingMode;
  10515. this.updateTextureSamplingMode(samplingMode, texture);
  10516. this._internalTexturesCache.push(texture);
  10517. return texture;
  10518. };
  10519. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10520. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10521. if (texture.isCube) {
  10522. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10523. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10524. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10525. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10526. }
  10527. else if (texture.is3D) {
  10528. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  10529. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10530. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10531. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  10532. }
  10533. else {
  10534. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10535. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10536. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10537. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10538. }
  10539. texture.samplingMode = samplingMode;
  10540. };
  10541. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10542. if (premulAlpha === void 0) { premulAlpha = false; }
  10543. if (!texture) {
  10544. return;
  10545. }
  10546. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10547. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10548. if (premulAlpha) {
  10549. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10550. }
  10551. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10552. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10553. if (texture.generateMipMaps) {
  10554. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10555. }
  10556. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10557. if (premulAlpha) {
  10558. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10559. }
  10560. this.resetTextureCache();
  10561. texture.isReady = true;
  10562. };
  10563. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10564. if (!texture || texture._isDisabled) {
  10565. return;
  10566. }
  10567. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10568. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10569. try {
  10570. // Testing video texture support
  10571. if (this._videoTextureSupported === undefined) {
  10572. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10573. if (this._gl.getError() !== 0) {
  10574. this._videoTextureSupported = false;
  10575. }
  10576. else {
  10577. this._videoTextureSupported = true;
  10578. }
  10579. }
  10580. // Copy video through the current working canvas if video texture is not supported
  10581. if (!this._videoTextureSupported) {
  10582. if (!texture._workingCanvas) {
  10583. texture._workingCanvas = document.createElement("canvas");
  10584. var context = texture._workingCanvas.getContext("2d");
  10585. if (!context) {
  10586. throw new Error("Unable to get 2d context");
  10587. }
  10588. texture._workingContext = context;
  10589. texture._workingCanvas.width = texture.width;
  10590. texture._workingCanvas.height = texture.height;
  10591. }
  10592. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10593. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10594. }
  10595. else {
  10596. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10597. }
  10598. if (texture.generateMipMaps) {
  10599. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10600. }
  10601. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10602. this.resetTextureCache();
  10603. texture.isReady = true;
  10604. }
  10605. catch (ex) {
  10606. // Something unexpected
  10607. // Let's disable the texture
  10608. texture._isDisabled = true;
  10609. }
  10610. };
  10611. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10612. var fullOptions = new RenderTargetCreationOptions();
  10613. if (options !== undefined && typeof options === "object") {
  10614. fullOptions.generateMipMaps = options.generateMipMaps;
  10615. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10616. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10617. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10618. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10619. }
  10620. else {
  10621. fullOptions.generateMipMaps = options;
  10622. fullOptions.generateDepthBuffer = true;
  10623. fullOptions.generateStencilBuffer = false;
  10624. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10625. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10626. }
  10627. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10628. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10629. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10630. }
  10631. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10632. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10633. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10634. }
  10635. var gl = this._gl;
  10636. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10637. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10638. var width = size.width || size;
  10639. var height = size.height || size;
  10640. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  10641. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10642. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10643. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10644. }
  10645. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10646. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10647. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10648. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10649. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10650. // Create the framebuffer
  10651. var framebuffer = gl.createFramebuffer();
  10652. this.bindUnboundFramebuffer(framebuffer);
  10653. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10654. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  10655. if (fullOptions.generateMipMaps) {
  10656. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10657. }
  10658. // Unbind
  10659. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10660. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10661. this.bindUnboundFramebuffer(null);
  10662. texture._framebuffer = framebuffer;
  10663. texture.baseWidth = width;
  10664. texture.baseHeight = height;
  10665. texture.width = width;
  10666. texture.height = height;
  10667. texture.isReady = true;
  10668. texture.samples = 1;
  10669. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  10670. texture.samplingMode = fullOptions.samplingMode;
  10671. texture.type = fullOptions.type;
  10672. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10673. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  10674. this.resetTextureCache();
  10675. this._internalTexturesCache.push(texture);
  10676. return texture;
  10677. };
  10678. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10679. var generateMipMaps = false;
  10680. var generateDepthBuffer = true;
  10681. var generateStencilBuffer = false;
  10682. var generateDepthTexture = false;
  10683. var textureCount = 1;
  10684. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10685. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10686. var types = [], samplingModes = [];
  10687. if (options !== undefined) {
  10688. generateMipMaps = options.generateMipMaps;
  10689. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10690. generateStencilBuffer = options.generateStencilBuffer;
  10691. generateDepthTexture = options.generateDepthTexture;
  10692. textureCount = options.textureCount || 1;
  10693. if (options.types) {
  10694. types = options.types;
  10695. }
  10696. if (options.samplingModes) {
  10697. samplingModes = options.samplingModes;
  10698. }
  10699. }
  10700. var gl = this._gl;
  10701. // Create the framebuffer
  10702. var framebuffer = gl.createFramebuffer();
  10703. this.bindUnboundFramebuffer(framebuffer);
  10704. var width = size.width || size;
  10705. var height = size.height || size;
  10706. var textures = [];
  10707. var attachments = [];
  10708. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10709. for (var i = 0; i < textureCount; i++) {
  10710. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10711. var type = types[i] || defaultType;
  10712. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10713. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10714. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10715. }
  10716. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10717. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10718. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10719. }
  10720. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10721. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10722. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10723. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10724. }
  10725. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10726. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10727. textures.push(texture);
  10728. attachments.push(attachment);
  10729. gl.activeTexture(gl["TEXTURE" + i]);
  10730. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10731. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10732. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10733. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10734. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10735. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10736. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10737. if (generateMipMaps) {
  10738. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10739. }
  10740. // Unbind
  10741. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10742. texture._framebuffer = framebuffer;
  10743. texture._depthStencilBuffer = depthStencilBuffer;
  10744. texture.baseWidth = width;
  10745. texture.baseHeight = height;
  10746. texture.width = width;
  10747. texture.height = height;
  10748. texture.isReady = true;
  10749. texture.samples = 1;
  10750. texture.generateMipMaps = generateMipMaps;
  10751. texture.samplingMode = samplingMode;
  10752. texture.type = type;
  10753. texture._generateDepthBuffer = generateDepthBuffer;
  10754. texture._generateStencilBuffer = generateStencilBuffer;
  10755. this._internalTexturesCache.push(texture);
  10756. }
  10757. if (generateDepthTexture && this._caps.depthTextureExtension) {
  10758. // Depth texture
  10759. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10760. gl.activeTexture(gl.TEXTURE0);
  10761. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10762. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10763. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10764. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10765. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10766. 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);
  10767. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10768. depthTexture._framebuffer = framebuffer;
  10769. depthTexture.baseWidth = width;
  10770. depthTexture.baseHeight = height;
  10771. depthTexture.width = width;
  10772. depthTexture.height = height;
  10773. depthTexture.isReady = true;
  10774. depthTexture.samples = 1;
  10775. depthTexture.generateMipMaps = generateMipMaps;
  10776. depthTexture.samplingMode = gl.NEAREST;
  10777. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10778. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10779. textures.push(depthTexture);
  10780. this._internalTexturesCache.push(depthTexture);
  10781. }
  10782. gl.drawBuffers(attachments);
  10783. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10784. this.bindUnboundFramebuffer(null);
  10785. this.resetTextureCache();
  10786. return textures;
  10787. };
  10788. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10789. if (samples === void 0) { samples = 1; }
  10790. var depthStencilBuffer = null;
  10791. var gl = this._gl;
  10792. // Create the depth/stencil buffer
  10793. if (generateStencilBuffer) {
  10794. depthStencilBuffer = gl.createRenderbuffer();
  10795. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10796. if (samples > 1) {
  10797. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10798. }
  10799. else {
  10800. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10801. }
  10802. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10803. }
  10804. else if (generateDepthBuffer) {
  10805. depthStencilBuffer = gl.createRenderbuffer();
  10806. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10807. if (samples > 1) {
  10808. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10809. }
  10810. else {
  10811. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10812. }
  10813. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10814. }
  10815. return depthStencilBuffer;
  10816. };
  10817. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10818. if (this.webGLVersion < 2 || !texture) {
  10819. return 1;
  10820. }
  10821. if (texture.samples === samples) {
  10822. return samples;
  10823. }
  10824. var gl = this._gl;
  10825. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10826. // Dispose previous render buffers
  10827. if (texture._depthStencilBuffer) {
  10828. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10829. }
  10830. if (texture._MSAAFramebuffer) {
  10831. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10832. }
  10833. if (texture._MSAARenderBuffer) {
  10834. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10835. }
  10836. if (samples > 1) {
  10837. var framebuffer = gl.createFramebuffer();
  10838. if (!framebuffer) {
  10839. throw new Error("Unable to create multi sampled framebuffer");
  10840. }
  10841. texture._MSAAFramebuffer = framebuffer;
  10842. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10843. var colorRenderbuffer = gl.createRenderbuffer();
  10844. if (!colorRenderbuffer) {
  10845. throw new Error("Unable to create multi sampled framebuffer");
  10846. }
  10847. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10848. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10849. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10850. texture._MSAARenderBuffer = colorRenderbuffer;
  10851. }
  10852. else {
  10853. this.bindUnboundFramebuffer(texture._framebuffer);
  10854. }
  10855. texture.samples = samples;
  10856. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10857. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10858. this.bindUnboundFramebuffer(null);
  10859. return samples;
  10860. };
  10861. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10862. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10863. };
  10864. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10865. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10866. };
  10867. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10868. var gl = this._gl;
  10869. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10870. var generateMipMaps = true;
  10871. var generateDepthBuffer = true;
  10872. var generateStencilBuffer = false;
  10873. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10874. if (options !== undefined) {
  10875. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10876. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10877. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  10878. if (options.samplingMode !== undefined) {
  10879. samplingMode = options.samplingMode;
  10880. }
  10881. }
  10882. texture.isCube = true;
  10883. texture.generateMipMaps = generateMipMaps;
  10884. texture.samples = 1;
  10885. texture.samplingMode = samplingMode;
  10886. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10887. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10888. for (var face = 0; face < 6; face++) {
  10889. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10890. }
  10891. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10892. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10893. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10894. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10895. // Create the framebuffer
  10896. var framebuffer = gl.createFramebuffer();
  10897. this.bindUnboundFramebuffer(framebuffer);
  10898. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10899. // Mipmaps
  10900. if (texture.generateMipMaps) {
  10901. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10902. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10903. }
  10904. // Unbind
  10905. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10906. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10907. this.bindUnboundFramebuffer(null);
  10908. texture._framebuffer = framebuffer;
  10909. texture.width = size;
  10910. texture.height = size;
  10911. texture.isReady = true;
  10912. this.resetTextureCache();
  10913. this._internalTexturesCache.push(texture);
  10914. return texture;
  10915. };
  10916. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10917. var _this = this;
  10918. if (onLoad === void 0) { onLoad = null; }
  10919. if (onError === void 0) { onError = null; }
  10920. if (forcedExtension === void 0) { forcedExtension = null; }
  10921. var callback = function (loadData) {
  10922. if (!loadData) {
  10923. if (onLoad) {
  10924. onLoad(null);
  10925. }
  10926. return;
  10927. }
  10928. var texture = loadData.texture;
  10929. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10930. texture._lodGenerationScale = scale;
  10931. texture._lodGenerationOffset = offset;
  10932. if (_this._caps.textureLOD) {
  10933. // Do not add extra process if texture lod is supported.
  10934. if (onLoad) {
  10935. onLoad(texture);
  10936. }
  10937. return;
  10938. }
  10939. var mipSlices = 3;
  10940. var gl = _this._gl;
  10941. var width = loadData.width;
  10942. if (!width) {
  10943. return;
  10944. }
  10945. var textures = [];
  10946. for (var i = 0; i < mipSlices; i++) {
  10947. //compute LOD from even spacing in smoothness (matching shader calculation)
  10948. var smoothness = i / (mipSlices - 1);
  10949. var roughness = 1 - smoothness;
  10950. var minLODIndex = offset; // roughness = 0
  10951. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10952. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10953. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10954. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10955. glTextureFromLod.isCube = true;
  10956. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10957. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10958. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10959. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10960. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10961. if (loadData.isDDS) {
  10962. var info = loadData.info;
  10963. var data = loadData.data;
  10964. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10965. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10966. }
  10967. else {
  10968. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10969. }
  10970. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10971. // Wrap in a base texture for easy binding.
  10972. var lodTexture = new BABYLON.BaseTexture(scene);
  10973. lodTexture.isCube = true;
  10974. lodTexture._texture = glTextureFromLod;
  10975. glTextureFromLod.isReady = true;
  10976. textures.push(lodTexture);
  10977. }
  10978. texture._lodTextureHigh = textures[2];
  10979. texture._lodTextureMid = textures[1];
  10980. texture._lodTextureLow = textures[0];
  10981. if (onLoad) {
  10982. onLoad(texture);
  10983. }
  10984. };
  10985. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10986. };
  10987. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10988. var _this = this;
  10989. if (onLoad === void 0) { onLoad = null; }
  10990. if (onError === void 0) { onError = null; }
  10991. if (forcedExtension === void 0) { forcedExtension = null; }
  10992. var gl = this._gl;
  10993. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10994. texture.isCube = true;
  10995. texture.url = rootUrl;
  10996. texture.generateMipMaps = !noMipmap;
  10997. if (!this._doNotHandleContextLost) {
  10998. texture._extension = forcedExtension;
  10999. texture._files = files;
  11000. }
  11001. var isKTX = false;
  11002. var isDDS = false;
  11003. var lastDot = rootUrl.lastIndexOf('.');
  11004. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  11005. if (this._textureFormatInUse) {
  11006. extension = this._textureFormatInUse;
  11007. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  11008. isKTX = true;
  11009. }
  11010. else {
  11011. isDDS = (extension === ".dds");
  11012. }
  11013. var onerror = function (request, exception) {
  11014. if (onError) {
  11015. onError(request.status + " " + request.statusText, exception);
  11016. }
  11017. };
  11018. if (isKTX) {
  11019. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  11020. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  11021. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  11022. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11023. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  11024. ktx.uploadLevels(_this._gl, !noMipmap);
  11025. _this.setCubeMapTextureParams(gl, loadMipmap);
  11026. texture.width = ktx.pixelWidth;
  11027. texture.height = ktx.pixelHeight;
  11028. texture.isReady = true;
  11029. }, undefined, undefined, true, onerror);
  11030. }
  11031. else if (isDDS) {
  11032. if (files && files.length === 6) {
  11033. cascadeLoadFiles(rootUrl, scene, function (imgs) {
  11034. var info;
  11035. var loadMipmap = false;
  11036. var width = 0;
  11037. for (var index = 0; index < imgs.length; index++) {
  11038. var data = imgs[index];
  11039. info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  11040. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  11041. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11042. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  11043. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  11044. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  11045. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11046. }
  11047. texture.width = info.width;
  11048. texture.height = info.height;
  11049. texture.type = info.textureType;
  11050. width = info.width;
  11051. }
  11052. _this.setCubeMapTextureParams(gl, loadMipmap);
  11053. texture.isReady = true;
  11054. if (onLoad) {
  11055. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  11056. }
  11057. }, files, onError);
  11058. }
  11059. else {
  11060. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  11061. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  11062. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  11063. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11064. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  11065. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  11066. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  11067. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11068. }
  11069. _this.setCubeMapTextureParams(gl, loadMipmap);
  11070. texture.width = info.width;
  11071. texture.height = info.height;
  11072. texture.isReady = true;
  11073. texture.type = info.textureType;
  11074. if (onLoad) {
  11075. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  11076. }
  11077. }, undefined, undefined, true, onerror);
  11078. }
  11079. }
  11080. else {
  11081. if (!files) {
  11082. throw new Error("Cannot load cubemap because files were not defined");
  11083. }
  11084. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  11085. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  11086. var height = width;
  11087. _this._prepareWorkingCanvas();
  11088. if (!_this._workingCanvas || !_this._workingContext) {
  11089. return;
  11090. }
  11091. _this._workingCanvas.width = width;
  11092. _this._workingCanvas.height = height;
  11093. var faces = [
  11094. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  11095. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  11096. ];
  11097. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11098. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11099. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  11100. for (var index = 0; index < faces.length; index++) {
  11101. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  11102. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  11103. }
  11104. if (!noMipmap) {
  11105. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11106. }
  11107. _this.setCubeMapTextureParams(gl, !noMipmap);
  11108. texture.width = width;
  11109. texture.height = height;
  11110. texture.isReady = true;
  11111. if (format) {
  11112. texture.format = format;
  11113. }
  11114. texture.onLoadedObservable.notifyObservers(texture);
  11115. texture.onLoadedObservable.clear();
  11116. if (onLoad) {
  11117. onLoad();
  11118. }
  11119. }, files, onError);
  11120. }
  11121. this._internalTexturesCache.push(texture);
  11122. return texture;
  11123. };
  11124. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  11125. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11126. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  11127. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11128. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11129. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11130. this.resetTextureCache();
  11131. };
  11132. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  11133. if (compression === void 0) { compression = null; }
  11134. if (level === void 0) { level = 0; }
  11135. texture._bufferViewArray = data;
  11136. texture.format = format;
  11137. texture.type = type;
  11138. texture.invertY = invertY;
  11139. texture._compression = compression;
  11140. var gl = this._gl;
  11141. var textureType = this._getWebGLTextureType(type);
  11142. var internalFormat = this._getInternalFormat(format);
  11143. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11144. var needConversion = false;
  11145. if (internalFormat === gl.RGB) {
  11146. internalFormat = gl.RGBA;
  11147. needConversion = true;
  11148. }
  11149. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11150. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11151. if (texture.width % 4 !== 0) {
  11152. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  11153. }
  11154. // Data are known to be in +X +Y +Z -X -Y -Z
  11155. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11156. var faceData = data[faceIndex];
  11157. if (compression) {
  11158. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  11159. }
  11160. else {
  11161. if (needConversion) {
  11162. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  11163. }
  11164. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  11165. }
  11166. }
  11167. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11168. if (isPot && texture.generateMipMaps && level === 0) {
  11169. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11170. }
  11171. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11172. this.resetTextureCache();
  11173. texture.isReady = true;
  11174. };
  11175. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  11176. if (compression === void 0) { compression = null; }
  11177. var gl = this._gl;
  11178. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  11179. texture.isCube = true;
  11180. texture.generateMipMaps = generateMipMaps;
  11181. texture.format = format;
  11182. texture.type = type;
  11183. if (!this._doNotHandleContextLost) {
  11184. texture._bufferViewArray = data;
  11185. }
  11186. var textureType = this._getWebGLTextureType(type);
  11187. var internalFormat = this._getInternalFormat(format);
  11188. if (internalFormat === gl.RGB) {
  11189. internalFormat = gl.RGBA;
  11190. }
  11191. var width = size;
  11192. var height = width;
  11193. texture.width = width;
  11194. texture.height = height;
  11195. // Double check on POT to generate Mips.
  11196. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11197. if (!isPot) {
  11198. generateMipMaps = false;
  11199. }
  11200. // Upload data if needed. The texture won't be ready until then.
  11201. if (data) {
  11202. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  11203. }
  11204. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  11205. // Filters
  11206. if (data && generateMipMaps) {
  11207. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11208. }
  11209. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  11210. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11211. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11212. }
  11213. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  11214. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11215. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11216. }
  11217. else {
  11218. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11219. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  11220. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  11221. }
  11222. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11223. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11224. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11225. return texture;
  11226. };
  11227. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  11228. var _this = this;
  11229. if (onLoad === void 0) { onLoad = null; }
  11230. if (onError === void 0) { onError = null; }
  11231. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11232. if (invertY === void 0) { invertY = false; }
  11233. var gl = this._gl;
  11234. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  11235. scene._addPendingData(texture);
  11236. texture.url = url;
  11237. this._internalTexturesCache.push(texture);
  11238. var onerror = function (request, exception) {
  11239. scene._removePendingData(texture);
  11240. if (onError) {
  11241. onError(request.status + " " + request.statusText, exception);
  11242. }
  11243. };
  11244. var internalCallback = function (data) {
  11245. var width = texture.width;
  11246. var faceDataArrays = callback(data);
  11247. if (!faceDataArrays) {
  11248. return;
  11249. }
  11250. if (mipmmapGenerator) {
  11251. var textureType = _this._getWebGLTextureType(type);
  11252. var internalFormat = _this._getInternalFormat(format);
  11253. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  11254. var needConversion = false;
  11255. if (internalFormat === gl.RGB) {
  11256. internalFormat = gl.RGBA;
  11257. needConversion = true;
  11258. }
  11259. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11260. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11261. var mipData = mipmmapGenerator(faceDataArrays);
  11262. for (var level = 0; level < mipData.length; level++) {
  11263. var mipSize = width >> level;
  11264. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11265. var mipFaceData = mipData[level][faceIndex];
  11266. if (needConversion) {
  11267. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  11268. }
  11269. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  11270. }
  11271. }
  11272. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11273. }
  11274. else {
  11275. texture.generateMipMaps = !noMipmap;
  11276. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  11277. }
  11278. texture.isReady = true;
  11279. _this.resetTextureCache();
  11280. scene._removePendingData(texture);
  11281. if (onLoad) {
  11282. onLoad();
  11283. }
  11284. };
  11285. BABYLON.Tools.LoadFile(url, function (data) {
  11286. internalCallback(data);
  11287. }, undefined, scene.database, true, onerror);
  11288. return texture;
  11289. };
  11290. ;
  11291. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  11292. if (compression === void 0) { compression = null; }
  11293. var internalFormat = this._getInternalFormat(format);
  11294. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11295. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11296. if (!this._doNotHandleContextLost) {
  11297. texture._bufferView = data;
  11298. texture.format = format;
  11299. texture.invertY = invertY;
  11300. texture._compression = compression;
  11301. }
  11302. if (texture.width % 4 !== 0) {
  11303. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11304. }
  11305. if (compression && data) {
  11306. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  11307. }
  11308. else {
  11309. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  11310. }
  11311. if (texture.generateMipMaps) {
  11312. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11313. }
  11314. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11315. this.resetTextureCache();
  11316. texture.isReady = true;
  11317. };
  11318. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  11319. if (compression === void 0) { compression = null; }
  11320. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  11321. texture.baseWidth = width;
  11322. texture.baseHeight = height;
  11323. texture.baseDepth = depth;
  11324. texture.width = width;
  11325. texture.height = height;
  11326. texture.depth = depth;
  11327. texture.format = format;
  11328. texture.generateMipMaps = generateMipMaps;
  11329. texture.samplingMode = samplingMode;
  11330. texture.is3D = true;
  11331. if (!this._doNotHandleContextLost) {
  11332. texture._bufferView = data;
  11333. }
  11334. this.updateRawTexture3D(texture, data, format, invertY, compression);
  11335. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11336. // Filters
  11337. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11338. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11339. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11340. if (generateMipMaps) {
  11341. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11342. }
  11343. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11344. this._internalTexturesCache.push(texture);
  11345. return texture;
  11346. };
  11347. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  11348. var gl = this._gl;
  11349. if (!gl) {
  11350. return;
  11351. }
  11352. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  11353. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11354. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11355. if (!noMipmap && !isCompressed) {
  11356. gl.generateMipmap(gl.TEXTURE_2D);
  11357. }
  11358. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11359. this.resetTextureCache();
  11360. if (scene) {
  11361. scene._removePendingData(texture);
  11362. }
  11363. texture.onLoadedObservable.notifyObservers(texture);
  11364. texture.onLoadedObservable.clear();
  11365. };
  11366. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  11367. var _this = this;
  11368. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11369. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  11370. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  11371. var gl = this._gl;
  11372. if (!gl) {
  11373. return;
  11374. }
  11375. if (!texture._webGLTexture) {
  11376. this.resetTextureCache();
  11377. if (scene) {
  11378. scene._removePendingData(texture);
  11379. }
  11380. return;
  11381. }
  11382. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11383. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11384. texture.baseWidth = width;
  11385. texture.baseHeight = height;
  11386. texture.width = potWidth;
  11387. texture.height = potHeight;
  11388. texture.isReady = true;
  11389. if (processFunction(potWidth, potHeight, function () {
  11390. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11391. })) {
  11392. // Returning as texture needs extra async steps
  11393. return;
  11394. }
  11395. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11396. };
  11397. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  11398. // Create new RGBA data container.
  11399. var rgbaData;
  11400. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  11401. rgbaData = new Float32Array(width * height * 4);
  11402. }
  11403. else {
  11404. rgbaData = new Uint32Array(width * height * 4);
  11405. }
  11406. // Convert each pixel.
  11407. for (var x = 0; x < width; x++) {
  11408. for (var y = 0; y < height; y++) {
  11409. var index = (y * width + x) * 3;
  11410. var newIndex = (y * width + x) * 4;
  11411. // Map Old Value to new value.
  11412. rgbaData[newIndex + 0] = rgbData[index + 0];
  11413. rgbaData[newIndex + 1] = rgbData[index + 1];
  11414. rgbaData[newIndex + 2] = rgbData[index + 2];
  11415. // Add fully opaque alpha channel.
  11416. rgbaData[newIndex + 3] = 1;
  11417. }
  11418. }
  11419. return rgbaData;
  11420. };
  11421. Engine.prototype._releaseFramebufferObjects = function (texture) {
  11422. var gl = this._gl;
  11423. if (texture._framebuffer) {
  11424. gl.deleteFramebuffer(texture._framebuffer);
  11425. texture._framebuffer = null;
  11426. }
  11427. if (texture._depthStencilBuffer) {
  11428. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11429. texture._depthStencilBuffer = null;
  11430. }
  11431. if (texture._MSAAFramebuffer) {
  11432. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11433. texture._MSAAFramebuffer = null;
  11434. }
  11435. if (texture._MSAARenderBuffer) {
  11436. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11437. texture._MSAARenderBuffer = null;
  11438. }
  11439. };
  11440. Engine.prototype._releaseTexture = function (texture) {
  11441. var gl = this._gl;
  11442. this._releaseFramebufferObjects(texture);
  11443. gl.deleteTexture(texture._webGLTexture);
  11444. // Unbind channels
  11445. this.unbindAllTextures();
  11446. var index = this._internalTexturesCache.indexOf(texture);
  11447. if (index !== -1) {
  11448. this._internalTexturesCache.splice(index, 1);
  11449. }
  11450. // Integrated fixed lod samplers.
  11451. if (texture._lodTextureHigh) {
  11452. texture._lodTextureHigh.dispose();
  11453. }
  11454. if (texture._lodTextureMid) {
  11455. texture._lodTextureMid.dispose();
  11456. }
  11457. if (texture._lodTextureLow) {
  11458. texture._lodTextureLow.dispose();
  11459. }
  11460. };
  11461. Engine.prototype.setProgram = function (program) {
  11462. if (this._currentProgram !== program) {
  11463. this._gl.useProgram(program);
  11464. this._currentProgram = program;
  11465. }
  11466. };
  11467. Engine.prototype.bindSamplers = function (effect) {
  11468. this.setProgram(effect.getProgram());
  11469. var samplers = effect.getSamplers();
  11470. for (var index = 0; index < samplers.length; index++) {
  11471. var uniform = effect.getUniform(samplers[index]);
  11472. this._gl.uniform1i(uniform, index);
  11473. }
  11474. this._currentEffect = null;
  11475. };
  11476. Engine.prototype.activateTextureChannel = function (textureChannel) {
  11477. if (this._activeTextureChannel !== textureChannel) {
  11478. this._gl.activeTexture(textureChannel);
  11479. this._activeTextureChannel = textureChannel;
  11480. }
  11481. };
  11482. Engine.prototype._bindTextureDirectly = function (target, texture) {
  11483. if (this._activeTexturesCache[this._activeTextureChannel] !== texture) {
  11484. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  11485. this._activeTexturesCache[this._activeTextureChannel] = texture;
  11486. }
  11487. };
  11488. Engine.prototype._bindTexture = function (channel, texture) {
  11489. if (channel < 0) {
  11490. return;
  11491. }
  11492. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11493. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  11494. };
  11495. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  11496. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  11497. };
  11498. Engine.prototype.unbindAllTextures = function () {
  11499. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  11500. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11501. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11502. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11503. if (this.webGLVersion > 1) {
  11504. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11505. }
  11506. }
  11507. };
  11508. Engine.prototype.setTexture = function (channel, uniform, texture) {
  11509. if (channel < 0) {
  11510. return;
  11511. }
  11512. if (this._setTexture(channel, texture)) {
  11513. this._gl.uniform1i(uniform, channel);
  11514. }
  11515. };
  11516. Engine.prototype._setTexture = function (channel, texture) {
  11517. // Not ready?
  11518. if (!texture) {
  11519. if (this._activeTexturesCache[channel] != null) {
  11520. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11521. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11522. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11523. if (this.webGLVersion > 1) {
  11524. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11525. }
  11526. }
  11527. return false;
  11528. }
  11529. // Video
  11530. var alreadyActivated = false;
  11531. if (texture.video) {
  11532. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11533. alreadyActivated = true;
  11534. texture.update();
  11535. }
  11536. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  11537. texture.delayLoad();
  11538. return false;
  11539. }
  11540. var internalTexture;
  11541. if (texture.isReady()) {
  11542. internalTexture = texture.getInternalTexture();
  11543. }
  11544. else if (texture.isCube) {
  11545. internalTexture = this.emptyCubeTexture;
  11546. }
  11547. else if (texture.is3D) {
  11548. internalTexture = this.emptyTexture3D;
  11549. }
  11550. else {
  11551. internalTexture = this.emptyTexture;
  11552. }
  11553. if (!alreadyActivated) {
  11554. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11555. }
  11556. if (this._activeTexturesCache[this._activeTextureChannel] === internalTexture) {
  11557. return false;
  11558. }
  11559. if (internalTexture && internalTexture.is3D) {
  11560. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture);
  11561. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11562. internalTexture._cachedWrapU = texture.wrapU;
  11563. switch (texture.wrapU) {
  11564. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11565. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11566. break;
  11567. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11568. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11569. break;
  11570. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11571. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11572. break;
  11573. }
  11574. }
  11575. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11576. internalTexture._cachedWrapV = texture.wrapV;
  11577. switch (texture.wrapV) {
  11578. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11579. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11580. break;
  11581. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11582. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11583. break;
  11584. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11585. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11586. break;
  11587. }
  11588. }
  11589. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  11590. internalTexture._cachedWrapR = texture.wrapR;
  11591. switch (texture.wrapV) {
  11592. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11593. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  11594. break;
  11595. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11596. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  11597. break;
  11598. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11599. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  11600. break;
  11601. }
  11602. }
  11603. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  11604. }
  11605. else if (internalTexture && internalTexture.isCube) {
  11606. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  11607. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  11608. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  11609. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  11610. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  11611. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  11612. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  11613. }
  11614. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  11615. }
  11616. else {
  11617. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  11618. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11619. internalTexture._cachedWrapU = texture.wrapU;
  11620. switch (texture.wrapU) {
  11621. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11622. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11623. break;
  11624. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11625. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11626. break;
  11627. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11628. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11629. break;
  11630. }
  11631. }
  11632. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11633. internalTexture._cachedWrapV = texture.wrapV;
  11634. switch (texture.wrapV) {
  11635. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11636. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11637. break;
  11638. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11639. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11640. break;
  11641. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11642. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11643. break;
  11644. }
  11645. }
  11646. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  11647. }
  11648. return true;
  11649. };
  11650. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  11651. if (channel < 0 || !uniform) {
  11652. return;
  11653. }
  11654. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  11655. this._textureUnits = new Int32Array(textures.length);
  11656. }
  11657. for (var i = 0; i < textures.length; i++) {
  11658. this._textureUnits[i] = channel + i;
  11659. }
  11660. this._gl.uniform1iv(uniform, this._textureUnits);
  11661. for (var index = 0; index < textures.length; index++) {
  11662. this._setTexture(channel + index, textures[index]);
  11663. }
  11664. };
  11665. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  11666. var internalTexture = texture.getInternalTexture();
  11667. if (!internalTexture) {
  11668. return;
  11669. }
  11670. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  11671. var value = texture.anisotropicFilteringLevel;
  11672. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  11673. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  11674. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  11675. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  11676. }
  11677. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  11678. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  11679. internalTexture._cachedAnisotropicFilteringLevel = value;
  11680. }
  11681. };
  11682. Engine.prototype.readPixels = function (x, y, width, height) {
  11683. var data = new Uint8Array(height * width * 4);
  11684. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  11685. return data;
  11686. };
  11687. /**
  11688. * Add an externaly attached data from its key.
  11689. * This method call will fail and return false, if such key already exists.
  11690. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  11691. * @param key the unique key that identifies the data
  11692. * @param data the data object to associate to the key for this Engine instance
  11693. * @return true if no such key were already present and the data was added successfully, false otherwise
  11694. */
  11695. Engine.prototype.addExternalData = function (key, data) {
  11696. if (!this._externalData) {
  11697. this._externalData = new BABYLON.StringDictionary();
  11698. }
  11699. return this._externalData.add(key, data);
  11700. };
  11701. /**
  11702. * Get an externaly attached data from its key
  11703. * @param key the unique key that identifies the data
  11704. * @return the associated data, if present (can be null), or undefined if not present
  11705. */
  11706. Engine.prototype.getExternalData = function (key) {
  11707. if (!this._externalData) {
  11708. this._externalData = new BABYLON.StringDictionary();
  11709. }
  11710. return this._externalData.get(key);
  11711. };
  11712. /**
  11713. * Get an externaly attached data from its key, create it using a factory if it's not already present
  11714. * @param key the unique key that identifies the data
  11715. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  11716. * @return the associated data, can be null if the factory returned null.
  11717. */
  11718. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  11719. if (!this._externalData) {
  11720. this._externalData = new BABYLON.StringDictionary();
  11721. }
  11722. return this._externalData.getOrAddWithFactory(key, factory);
  11723. };
  11724. /**
  11725. * Remove an externaly attached data from the Engine instance
  11726. * @param key the unique key that identifies the data
  11727. * @return true if the data was successfully removed, false if it doesn't exist
  11728. */
  11729. Engine.prototype.removeExternalData = function (key) {
  11730. if (!this._externalData) {
  11731. this._externalData = new BABYLON.StringDictionary();
  11732. }
  11733. return this._externalData.remove(key);
  11734. };
  11735. Engine.prototype.unbindAllAttributes = function () {
  11736. if (this._mustWipeVertexAttributes) {
  11737. this._mustWipeVertexAttributes = false;
  11738. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11739. this._gl.disableVertexAttribArray(i);
  11740. this._vertexAttribArraysEnabled[i] = false;
  11741. this._currentBufferPointers[i].active = false;
  11742. }
  11743. return;
  11744. }
  11745. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11746. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11747. continue;
  11748. }
  11749. this._gl.disableVertexAttribArray(i);
  11750. this._vertexAttribArraysEnabled[i] = false;
  11751. this._currentBufferPointers[i].active = false;
  11752. }
  11753. };
  11754. Engine.prototype.releaseEffects = function () {
  11755. for (var name in this._compiledEffects) {
  11756. this._deleteProgram(this._compiledEffects[name]._program);
  11757. }
  11758. this._compiledEffects = {};
  11759. };
  11760. // Dispose
  11761. Engine.prototype.dispose = function () {
  11762. this.hideLoadingUI();
  11763. this.stopRenderLoop();
  11764. // Release postProcesses
  11765. while (this.postProcesses.length) {
  11766. this.postProcesses[0].dispose();
  11767. }
  11768. // Empty texture
  11769. if (this._emptyTexture) {
  11770. this._releaseTexture(this._emptyTexture);
  11771. this._emptyTexture = null;
  11772. }
  11773. if (this._emptyCubeTexture) {
  11774. this._releaseTexture(this._emptyCubeTexture);
  11775. this._emptyCubeTexture = null;
  11776. }
  11777. // Rescale PP
  11778. if (this._rescalePostProcess) {
  11779. this._rescalePostProcess.dispose();
  11780. }
  11781. // Release scenes
  11782. while (this.scenes.length) {
  11783. this.scenes[0].dispose();
  11784. }
  11785. // Release audio engine
  11786. if (Engine.audioEngine) {
  11787. Engine.audioEngine.dispose();
  11788. }
  11789. // Release effects
  11790. this.releaseEffects();
  11791. // Unbind
  11792. this.unbindAllAttributes();
  11793. if (this._dummyFramebuffer) {
  11794. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  11795. }
  11796. //WebVR
  11797. this.disableVR();
  11798. // Events
  11799. if (BABYLON.Tools.IsWindowObjectExist()) {
  11800. window.removeEventListener("blur", this._onBlur);
  11801. window.removeEventListener("focus", this._onFocus);
  11802. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  11803. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  11804. if (this._renderingCanvas) {
  11805. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  11806. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  11807. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  11808. if (!this._doNotHandleContextLost) {
  11809. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  11810. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  11811. }
  11812. }
  11813. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  11814. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  11815. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  11816. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  11817. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  11818. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  11819. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  11820. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  11821. if (this._onVrDisplayConnect) {
  11822. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11823. if (this._onVrDisplayDisconnect) {
  11824. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11825. }
  11826. if (this._onVrDisplayPresentChange) {
  11827. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11828. }
  11829. this._onVrDisplayConnect = null;
  11830. this._onVrDisplayDisconnect = null;
  11831. }
  11832. }
  11833. // Remove from Instances
  11834. var index = Engine.Instances.indexOf(this);
  11835. if (index >= 0) {
  11836. Engine.Instances.splice(index, 1);
  11837. }
  11838. this._workingCanvas = null;
  11839. this._workingContext = null;
  11840. this._currentBufferPointers = [];
  11841. this._renderingCanvas = null;
  11842. this._currentProgram = null;
  11843. this.onResizeObservable.clear();
  11844. this.onCanvasBlurObservable.clear();
  11845. this.onCanvasFocusObservable.clear();
  11846. this.onCanvasPointerOutObservable.clear();
  11847. this.onBeginFrameObservable.clear();
  11848. this.onEndFrameObservable.clear();
  11849. BABYLON.Effect.ResetCache();
  11850. };
  11851. // Loading screen
  11852. Engine.prototype.displayLoadingUI = function () {
  11853. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11854. return;
  11855. }
  11856. var loadingScreen = this.loadingScreen;
  11857. if (loadingScreen) {
  11858. loadingScreen.displayLoadingUI();
  11859. }
  11860. };
  11861. Engine.prototype.hideLoadingUI = function () {
  11862. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11863. return;
  11864. }
  11865. var loadingScreen = this.loadingScreen;
  11866. if (loadingScreen) {
  11867. loadingScreen.hideLoadingUI();
  11868. }
  11869. };
  11870. Object.defineProperty(Engine.prototype, "loadingScreen", {
  11871. get: function () {
  11872. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  11873. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  11874. return this._loadingScreen;
  11875. },
  11876. set: function (loadingScreen) {
  11877. this._loadingScreen = loadingScreen;
  11878. },
  11879. enumerable: true,
  11880. configurable: true
  11881. });
  11882. Object.defineProperty(Engine.prototype, "loadingUIText", {
  11883. set: function (text) {
  11884. this.loadingScreen.loadingUIText = text;
  11885. },
  11886. enumerable: true,
  11887. configurable: true
  11888. });
  11889. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  11890. set: function (color) {
  11891. this.loadingScreen.loadingUIBackgroundColor = color;
  11892. },
  11893. enumerable: true,
  11894. configurable: true
  11895. });
  11896. Engine.prototype.attachContextLostEvent = function (callback) {
  11897. if (this._renderingCanvas) {
  11898. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  11899. }
  11900. };
  11901. Engine.prototype.attachContextRestoredEvent = function (callback) {
  11902. if (this._renderingCanvas) {
  11903. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  11904. }
  11905. };
  11906. Engine.prototype.getVertexShaderSource = function (program) {
  11907. var shaders = this._gl.getAttachedShaders(program);
  11908. if (!shaders) {
  11909. return null;
  11910. }
  11911. return this._gl.getShaderSource(shaders[0]);
  11912. };
  11913. Engine.prototype.getFragmentShaderSource = function (program) {
  11914. var shaders = this._gl.getAttachedShaders(program);
  11915. if (!shaders) {
  11916. return null;
  11917. }
  11918. return this._gl.getShaderSource(shaders[1]);
  11919. };
  11920. Engine.prototype.getError = function () {
  11921. return this._gl.getError();
  11922. };
  11923. // FPS
  11924. Engine.prototype.getFps = function () {
  11925. return this._fps;
  11926. };
  11927. Engine.prototype.getDeltaTime = function () {
  11928. return this._deltaTime;
  11929. };
  11930. Engine.prototype._measureFps = function () {
  11931. this._performanceMonitor.sampleFrame();
  11932. this._fps = this._performanceMonitor.averageFPS;
  11933. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  11934. };
  11935. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  11936. if (faceIndex === void 0) { faceIndex = -1; }
  11937. var gl = this._gl;
  11938. if (!this._dummyFramebuffer) {
  11939. var dummy = gl.createFramebuffer();
  11940. if (!dummy) {
  11941. throw new Error("Unable to create dummy framebuffer");
  11942. }
  11943. this._dummyFramebuffer = dummy;
  11944. }
  11945. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  11946. if (faceIndex > -1) {
  11947. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11948. }
  11949. else {
  11950. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11951. }
  11952. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  11953. var buffer;
  11954. switch (readType) {
  11955. case gl.UNSIGNED_BYTE:
  11956. buffer = new Uint8Array(4 * width * height);
  11957. readType = gl.UNSIGNED_BYTE;
  11958. break;
  11959. default:
  11960. buffer = new Float32Array(4 * width * height);
  11961. readType = gl.FLOAT;
  11962. break;
  11963. }
  11964. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  11965. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  11966. return buffer;
  11967. };
  11968. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11969. if (this._webGLVersion > 1) {
  11970. return this._caps.colorBufferFloat;
  11971. }
  11972. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11973. };
  11974. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11975. if (this._webGLVersion > 1) {
  11976. return this._caps.colorBufferFloat;
  11977. }
  11978. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11979. };
  11980. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11981. Engine.prototype._canRenderToFramebuffer = function (type) {
  11982. var gl = this._gl;
  11983. //clear existing errors
  11984. while (gl.getError() !== gl.NO_ERROR) { }
  11985. var successful = true;
  11986. var texture = gl.createTexture();
  11987. gl.bindTexture(gl.TEXTURE_2D, texture);
  11988. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11989. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11990. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11991. var fb = gl.createFramebuffer();
  11992. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11993. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11994. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  11995. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  11996. successful = successful && (gl.getError() === gl.NO_ERROR);
  11997. //try render by clearing frame buffer's color buffer
  11998. if (successful) {
  11999. gl.clear(gl.COLOR_BUFFER_BIT);
  12000. successful = successful && (gl.getError() === gl.NO_ERROR);
  12001. }
  12002. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  12003. if (successful) {
  12004. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  12005. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12006. var readFormat = gl.RGBA;
  12007. var readType = gl.UNSIGNED_BYTE;
  12008. var buffer = new Uint8Array(4);
  12009. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  12010. successful = successful && (gl.getError() === gl.NO_ERROR);
  12011. }
  12012. //clean up
  12013. gl.deleteTexture(texture);
  12014. gl.deleteFramebuffer(fb);
  12015. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12016. //clear accumulated errors
  12017. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  12018. return successful;
  12019. };
  12020. Engine.prototype._getWebGLTextureType = function (type) {
  12021. if (type === Engine.TEXTURETYPE_FLOAT) {
  12022. return this._gl.FLOAT;
  12023. }
  12024. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  12025. // Add Half Float Constant.
  12026. return this._gl.HALF_FLOAT_OES;
  12027. }
  12028. return this._gl.UNSIGNED_BYTE;
  12029. };
  12030. ;
  12031. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  12032. if (this._webGLVersion === 1) {
  12033. return this._gl.RGBA;
  12034. }
  12035. if (type === Engine.TEXTURETYPE_FLOAT) {
  12036. return this._gl.RGBA32F;
  12037. }
  12038. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  12039. return this._gl.RGBA16F;
  12040. }
  12041. return this._gl.RGBA;
  12042. };
  12043. ;
  12044. Engine.prototype.createQuery = function () {
  12045. return this._gl.createQuery();
  12046. };
  12047. Engine.prototype.deleteQuery = function (query) {
  12048. this._gl.deleteQuery(query);
  12049. return this;
  12050. };
  12051. Engine.prototype.isQueryResultAvailable = function (query) {
  12052. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  12053. };
  12054. Engine.prototype.getQueryResult = function (query) {
  12055. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  12056. };
  12057. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  12058. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  12059. this._gl.beginQuery(glAlgorithm, query);
  12060. return this;
  12061. };
  12062. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  12063. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  12064. this._gl.endQuery(glAlgorithm);
  12065. return this;
  12066. };
  12067. /* Time queries */
  12068. Engine.prototype._createTimeQuery = function () {
  12069. var timerQuery = this._caps.timerQuery;
  12070. if (timerQuery.createQueryEXT) {
  12071. return timerQuery.createQueryEXT();
  12072. }
  12073. return this.createQuery();
  12074. };
  12075. Engine.prototype._deleteTimeQuery = function (query) {
  12076. var timerQuery = this._caps.timerQuery;
  12077. if (timerQuery.deleteQueryEXT) {
  12078. timerQuery.deleteQueryEXT(query);
  12079. return;
  12080. }
  12081. this.deleteQuery(query);
  12082. };
  12083. Engine.prototype._getTimeQueryResult = function (query) {
  12084. var timerQuery = this._caps.timerQuery;
  12085. if (timerQuery.getQueryObjectEXT) {
  12086. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  12087. }
  12088. return this.getQueryResult(query);
  12089. };
  12090. Engine.prototype._getTimeQueryAvailability = function (query) {
  12091. var timerQuery = this._caps.timerQuery;
  12092. if (timerQuery.getQueryObjectEXT) {
  12093. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  12094. }
  12095. return this.isQueryResultAvailable(query);
  12096. };
  12097. Engine.prototype.startTimeQuery = function () {
  12098. var timerQuery = this._caps.timerQuery;
  12099. if (!timerQuery) {
  12100. return null;
  12101. }
  12102. var token = new BABYLON._TimeToken();
  12103. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12104. if (this._caps.canUseTimestampForTimerQuery) {
  12105. token._startTimeQuery = this._createTimeQuery();
  12106. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  12107. }
  12108. else {
  12109. if (this._currentNonTimestampToken) {
  12110. return this._currentNonTimestampToken;
  12111. }
  12112. token._timeElapsedQuery = this._createTimeQuery();
  12113. if (timerQuery.beginQueryEXT) {
  12114. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12115. }
  12116. else {
  12117. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12118. }
  12119. this._currentNonTimestampToken = token;
  12120. }
  12121. return token;
  12122. };
  12123. Engine.prototype.endTimeQuery = function (token) {
  12124. var timerQuery = this._caps.timerQuery;
  12125. if (!timerQuery || !token) {
  12126. return -1;
  12127. }
  12128. if (this._caps.canUseTimestampForTimerQuery) {
  12129. if (!token._startTimeQuery) {
  12130. return -1;
  12131. }
  12132. if (!token._endTimeQuery) {
  12133. token._endTimeQuery = this._createTimeQuery();
  12134. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  12135. }
  12136. }
  12137. else if (!token._timeElapsedQueryEnded) {
  12138. if (!token._timeElapsedQuery) {
  12139. return -1;
  12140. }
  12141. if (timerQuery.endQueryEXT) {
  12142. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  12143. }
  12144. else {
  12145. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  12146. }
  12147. token._timeElapsedQueryEnded = true;
  12148. }
  12149. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12150. var available = false;
  12151. if (token._endTimeQuery) {
  12152. available = this._getTimeQueryAvailability(token._endTimeQuery);
  12153. }
  12154. else if (token._timeElapsedQuery) {
  12155. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  12156. }
  12157. if (available && !disjoint) {
  12158. var result = 0;
  12159. if (this._caps.canUseTimestampForTimerQuery) {
  12160. if (!token._startTimeQuery || !token._endTimeQuery) {
  12161. return -1;
  12162. }
  12163. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  12164. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  12165. result = timeEnd - timeStart;
  12166. this._deleteTimeQuery(token._startTimeQuery);
  12167. this._deleteTimeQuery(token._endTimeQuery);
  12168. token._startTimeQuery = null;
  12169. token._endTimeQuery = null;
  12170. }
  12171. else {
  12172. if (!token._timeElapsedQuery) {
  12173. return -1;
  12174. }
  12175. result = this._getTimeQueryResult(token._timeElapsedQuery);
  12176. this._deleteTimeQuery(token._timeElapsedQuery);
  12177. token._timeElapsedQuery = null;
  12178. token._timeElapsedQueryEnded = false;
  12179. this._currentNonTimestampToken = null;
  12180. }
  12181. return result;
  12182. }
  12183. return -1;
  12184. };
  12185. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  12186. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  12187. };
  12188. // Transform feedback
  12189. Engine.prototype.createTransformFeedback = function () {
  12190. return this._gl.createTransformFeedback();
  12191. };
  12192. Engine.prototype.deleteTransformFeedback = function (value) {
  12193. this._gl.deleteTransformFeedback(value);
  12194. };
  12195. Engine.prototype.bindTransformFeedback = function (value) {
  12196. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  12197. };
  12198. Engine.prototype.beginTransformFeedback = function (usePoints) {
  12199. if (usePoints === void 0) { usePoints = true; }
  12200. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  12201. };
  12202. Engine.prototype.endTransformFeedback = function () {
  12203. this._gl.endTransformFeedback();
  12204. };
  12205. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  12206. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  12207. };
  12208. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  12209. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  12210. };
  12211. // Statics
  12212. Engine.isSupported = function () {
  12213. try {
  12214. var tempcanvas = document.createElement("canvas");
  12215. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  12216. return gl != null && !!window.WebGLRenderingContext;
  12217. }
  12218. catch (e) {
  12219. return false;
  12220. }
  12221. };
  12222. Engine.Instances = new Array();
  12223. // Const statics
  12224. Engine._ALPHA_DISABLE = 0;
  12225. Engine._ALPHA_ADD = 1;
  12226. Engine._ALPHA_COMBINE = 2;
  12227. Engine._ALPHA_SUBTRACT = 3;
  12228. Engine._ALPHA_MULTIPLY = 4;
  12229. Engine._ALPHA_MAXIMIZED = 5;
  12230. Engine._ALPHA_ONEONE = 6;
  12231. Engine._ALPHA_PREMULTIPLIED = 7;
  12232. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  12233. Engine._ALPHA_INTERPOLATE = 9;
  12234. Engine._ALPHA_SCREENMODE = 10;
  12235. Engine._DELAYLOADSTATE_NONE = 0;
  12236. Engine._DELAYLOADSTATE_LOADED = 1;
  12237. Engine._DELAYLOADSTATE_LOADING = 2;
  12238. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  12239. Engine._TEXTUREFORMAT_ALPHA = 0;
  12240. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  12241. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  12242. Engine._TEXTUREFORMAT_RGB = 4;
  12243. Engine._TEXTUREFORMAT_RGBA = 5;
  12244. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  12245. Engine._TEXTURETYPE_FLOAT = 1;
  12246. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  12247. // Depht or Stencil test Constants.
  12248. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  12249. 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.
  12250. 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.
  12251. 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.
  12252. 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.
  12253. 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.
  12254. 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.
  12255. 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.
  12256. // Stencil Actions Constants.
  12257. Engine._KEEP = 0x1E00;
  12258. Engine._REPLACE = 0x1E01;
  12259. Engine._INCR = 0x1E02;
  12260. Engine._DECR = 0x1E03;
  12261. Engine._INVERT = 0x150A;
  12262. Engine._INCR_WRAP = 0x8507;
  12263. Engine._DECR_WRAP = 0x8508;
  12264. // Texture rescaling mode
  12265. Engine._SCALEMODE_FLOOR = 1;
  12266. Engine._SCALEMODE_NEAREST = 2;
  12267. Engine._SCALEMODE_CEILING = 3;
  12268. // Updatable statics so stick with vars here
  12269. Engine.CollisionsEpsilon = 0.001;
  12270. Engine.CodeRepository = "src/";
  12271. Engine.ShadersRepository = "src/Shaders/";
  12272. return Engine;
  12273. }());
  12274. BABYLON.Engine = Engine;
  12275. })(BABYLON || (BABYLON = {}));
  12276. //# sourceMappingURL=babylon.engine.js.map
  12277. var BABYLON;
  12278. (function (BABYLON) {
  12279. /**
  12280. * Node is the basic class for all scene objects (Mesh, Light Camera).
  12281. */
  12282. var Node = /** @class */ (function () {
  12283. /**
  12284. * @constructor
  12285. * @param {string} name - the name and id to be given to this node
  12286. * @param {BABYLON.Scene} the scene this node will be added to
  12287. */
  12288. function Node(name, scene) {
  12289. if (scene === void 0) { scene = null; }
  12290. this.state = "";
  12291. this.metadata = null;
  12292. this.doNotSerialize = false;
  12293. this.animations = new Array();
  12294. this._ranges = {};
  12295. this._isEnabled = true;
  12296. this._isReady = true;
  12297. this._currentRenderId = -1;
  12298. this._parentRenderId = -1;
  12299. /**
  12300. * An event triggered when the mesh is disposed.
  12301. * @type {BABYLON.Observable}
  12302. */
  12303. this.onDisposeObservable = new BABYLON.Observable();
  12304. // Behaviors
  12305. this._behaviors = new Array();
  12306. this.name = name;
  12307. this.id = name;
  12308. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  12309. this.uniqueId = this._scene.getUniqueId();
  12310. this._initCache();
  12311. }
  12312. Object.defineProperty(Node.prototype, "parent", {
  12313. get: function () {
  12314. return this._parentNode;
  12315. },
  12316. set: function (parent) {
  12317. if (this._parentNode === parent) {
  12318. return;
  12319. }
  12320. if (this._parentNode) {
  12321. var index = this._parentNode._children.indexOf(this);
  12322. if (index !== -1) {
  12323. this._parentNode._children.splice(index, 1);
  12324. }
  12325. }
  12326. this._parentNode = parent;
  12327. if (this._parentNode) {
  12328. if (!this._parentNode._children) {
  12329. this._parentNode._children = new Array();
  12330. }
  12331. this._parentNode._children.push(this);
  12332. }
  12333. },
  12334. enumerable: true,
  12335. configurable: true
  12336. });
  12337. Node.prototype.getClassName = function () {
  12338. return "Node";
  12339. };
  12340. Object.defineProperty(Node.prototype, "onDispose", {
  12341. set: function (callback) {
  12342. if (this._onDisposeObserver) {
  12343. this.onDisposeObservable.remove(this._onDisposeObserver);
  12344. }
  12345. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  12346. },
  12347. enumerable: true,
  12348. configurable: true
  12349. });
  12350. Node.prototype.getScene = function () {
  12351. return this._scene;
  12352. };
  12353. Node.prototype.getEngine = function () {
  12354. return this._scene.getEngine();
  12355. };
  12356. Node.prototype.addBehavior = function (behavior) {
  12357. var _this = this;
  12358. var index = this._behaviors.indexOf(behavior);
  12359. if (index !== -1) {
  12360. return this;
  12361. }
  12362. behavior.init();
  12363. if (this._scene.isLoading) {
  12364. // We defer the attach when the scene will be loaded
  12365. var observer = this._scene.onDataLoadedObservable.add(function () {
  12366. behavior.attach(_this);
  12367. _this._scene.onDataLoadedObservable.remove(observer);
  12368. });
  12369. }
  12370. else {
  12371. behavior.attach(this);
  12372. }
  12373. this._behaviors.push(behavior);
  12374. return this;
  12375. };
  12376. Node.prototype.removeBehavior = function (behavior) {
  12377. var index = this._behaviors.indexOf(behavior);
  12378. if (index === -1) {
  12379. return this;
  12380. }
  12381. this._behaviors[index].detach();
  12382. this._behaviors.splice(index, 1);
  12383. return this;
  12384. };
  12385. Object.defineProperty(Node.prototype, "behaviors", {
  12386. get: function () {
  12387. return this._behaviors;
  12388. },
  12389. enumerable: true,
  12390. configurable: true
  12391. });
  12392. Node.prototype.getBehaviorByName = function (name) {
  12393. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12394. var behavior = _a[_i];
  12395. if (behavior.name === name) {
  12396. return behavior;
  12397. }
  12398. }
  12399. return null;
  12400. };
  12401. // override it in derived class
  12402. Node.prototype.getWorldMatrix = function () {
  12403. return BABYLON.Matrix.Identity();
  12404. };
  12405. // override it in derived class if you add new variables to the cache
  12406. // and call the parent class method
  12407. Node.prototype._initCache = function () {
  12408. this._cache = {};
  12409. this._cache.parent = undefined;
  12410. };
  12411. Node.prototype.updateCache = function (force) {
  12412. if (!force && this.isSynchronized())
  12413. return;
  12414. this._cache.parent = this.parent;
  12415. this._updateCache();
  12416. };
  12417. // override it in derived class if you add new variables to the cache
  12418. // and call the parent class method if !ignoreParentClass
  12419. Node.prototype._updateCache = function (ignoreParentClass) {
  12420. };
  12421. // override it in derived class if you add new variables to the cache
  12422. Node.prototype._isSynchronized = function () {
  12423. return true;
  12424. };
  12425. Node.prototype._markSyncedWithParent = function () {
  12426. if (this.parent) {
  12427. this._parentRenderId = this.parent._currentRenderId;
  12428. }
  12429. };
  12430. Node.prototype.isSynchronizedWithParent = function () {
  12431. if (!this.parent) {
  12432. return true;
  12433. }
  12434. if (this._parentRenderId !== this.parent._currentRenderId) {
  12435. return false;
  12436. }
  12437. return this.parent.isSynchronized();
  12438. };
  12439. Node.prototype.isSynchronized = function (updateCache) {
  12440. var check = this.hasNewParent();
  12441. check = check || !this.isSynchronizedWithParent();
  12442. check = check || !this._isSynchronized();
  12443. if (updateCache)
  12444. this.updateCache(true);
  12445. return !check;
  12446. };
  12447. Node.prototype.hasNewParent = function (update) {
  12448. if (this._cache.parent === this.parent)
  12449. return false;
  12450. if (update)
  12451. this._cache.parent = this.parent;
  12452. return true;
  12453. };
  12454. /**
  12455. * Is this node ready to be used/rendered
  12456. * @return {boolean} is it ready
  12457. */
  12458. Node.prototype.isReady = function () {
  12459. return this._isReady;
  12460. };
  12461. /**
  12462. * Is this node enabled.
  12463. * If the node has a parent and is enabled, the parent will be inspected as well.
  12464. * @return {boolean} whether this node (and its parent) is enabled.
  12465. * @see setEnabled
  12466. */
  12467. Node.prototype.isEnabled = function () {
  12468. if (!this._isEnabled) {
  12469. return false;
  12470. }
  12471. if (this.parent) {
  12472. return this.parent.isEnabled();
  12473. }
  12474. return true;
  12475. };
  12476. /**
  12477. * Set the enabled state of this node.
  12478. * @param {boolean} value - the new enabled state
  12479. * @see isEnabled
  12480. */
  12481. Node.prototype.setEnabled = function (value) {
  12482. this._isEnabled = value;
  12483. };
  12484. /**
  12485. * Is this node a descendant of the given node.
  12486. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  12487. * @param {BABYLON.Node} ancestor - The parent node to inspect
  12488. * @see parent
  12489. */
  12490. Node.prototype.isDescendantOf = function (ancestor) {
  12491. if (this.parent) {
  12492. if (this.parent === ancestor) {
  12493. return true;
  12494. }
  12495. return this.parent.isDescendantOf(ancestor);
  12496. }
  12497. return false;
  12498. };
  12499. /**
  12500. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  12501. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  12502. * @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.
  12503. * @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.
  12504. */
  12505. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  12506. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  12507. if (!this._children) {
  12508. return;
  12509. }
  12510. for (var index = 0; index < this._children.length; index++) {
  12511. var item = this._children[index];
  12512. if (!predicate || predicate(item)) {
  12513. results.push(item);
  12514. }
  12515. if (!directDescendantsOnly) {
  12516. item._getDescendants(results, false, predicate);
  12517. }
  12518. }
  12519. };
  12520. /**
  12521. * Will return all nodes that have this node as ascendant.
  12522. * @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.
  12523. * @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.
  12524. * @return {BABYLON.Node[]} all children nodes of all types.
  12525. */
  12526. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  12527. var results = new Array();
  12528. this._getDescendants(results, directDescendantsOnly, predicate);
  12529. return results;
  12530. };
  12531. /**
  12532. * Get all child-meshes of this node.
  12533. */
  12534. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  12535. var results = [];
  12536. this._getDescendants(results, directDescendantsOnly, function (node) {
  12537. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  12538. });
  12539. return results;
  12540. };
  12541. /**
  12542. * Get all child-transformNodes of this node.
  12543. */
  12544. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  12545. var results = [];
  12546. this._getDescendants(results, directDescendantsOnly, function (node) {
  12547. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  12548. });
  12549. return results;
  12550. };
  12551. /**
  12552. * Get all direct children of this node.
  12553. */
  12554. Node.prototype.getChildren = function (predicate) {
  12555. return this.getDescendants(true, predicate);
  12556. };
  12557. Node.prototype._setReady = function (state) {
  12558. if (state === this._isReady) {
  12559. return;
  12560. }
  12561. if (!state) {
  12562. this._isReady = false;
  12563. return;
  12564. }
  12565. this._isReady = true;
  12566. if (this.onReady) {
  12567. this.onReady(this);
  12568. }
  12569. };
  12570. Node.prototype.getAnimationByName = function (name) {
  12571. for (var i = 0; i < this.animations.length; i++) {
  12572. var animation = this.animations[i];
  12573. if (animation.name === name) {
  12574. return animation;
  12575. }
  12576. }
  12577. return null;
  12578. };
  12579. Node.prototype.createAnimationRange = function (name, from, to) {
  12580. // check name not already in use
  12581. if (!this._ranges[name]) {
  12582. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  12583. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12584. if (this.animations[i]) {
  12585. this.animations[i].createRange(name, from, to);
  12586. }
  12587. }
  12588. }
  12589. };
  12590. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  12591. if (deleteFrames === void 0) { deleteFrames = true; }
  12592. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12593. if (this.animations[i]) {
  12594. this.animations[i].deleteRange(name, deleteFrames);
  12595. }
  12596. }
  12597. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  12598. };
  12599. Node.prototype.getAnimationRange = function (name) {
  12600. return this._ranges[name];
  12601. };
  12602. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  12603. var range = this.getAnimationRange(name);
  12604. if (!range) {
  12605. return;
  12606. }
  12607. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  12608. };
  12609. Node.prototype.serializeAnimationRanges = function () {
  12610. var serializationRanges = [];
  12611. for (var name in this._ranges) {
  12612. var localRange = this._ranges[name];
  12613. if (!localRange) {
  12614. continue;
  12615. }
  12616. var range = {};
  12617. range.name = name;
  12618. range.from = localRange.from;
  12619. range.to = localRange.to;
  12620. serializationRanges.push(range);
  12621. }
  12622. return serializationRanges;
  12623. };
  12624. Node.prototype.dispose = function () {
  12625. this.parent = null;
  12626. // Callback
  12627. this.onDisposeObservable.notifyObservers(this);
  12628. this.onDisposeObservable.clear();
  12629. // Behaviors
  12630. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12631. var behavior = _a[_i];
  12632. behavior.detach();
  12633. }
  12634. this._behaviors = [];
  12635. };
  12636. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  12637. if (parsedNode.ranges) {
  12638. for (var index = 0; index < parsedNode.ranges.length; index++) {
  12639. var data = parsedNode.ranges[index];
  12640. node.createAnimationRange(data.name, data.from, data.to);
  12641. }
  12642. }
  12643. };
  12644. __decorate([
  12645. BABYLON.serialize()
  12646. ], Node.prototype, "name", void 0);
  12647. __decorate([
  12648. BABYLON.serialize()
  12649. ], Node.prototype, "id", void 0);
  12650. __decorate([
  12651. BABYLON.serialize()
  12652. ], Node.prototype, "uniqueId", void 0);
  12653. __decorate([
  12654. BABYLON.serialize()
  12655. ], Node.prototype, "state", void 0);
  12656. __decorate([
  12657. BABYLON.serialize()
  12658. ], Node.prototype, "metadata", void 0);
  12659. return Node;
  12660. }());
  12661. BABYLON.Node = Node;
  12662. })(BABYLON || (BABYLON = {}));
  12663. //# sourceMappingURL=babylon.node.js.map
  12664. var BABYLON;
  12665. (function (BABYLON) {
  12666. var BoundingSphere = /** @class */ (function () {
  12667. function BoundingSphere(minimum, maximum) {
  12668. this.minimum = minimum;
  12669. this.maximum = maximum;
  12670. this._tempRadiusVector = BABYLON.Vector3.Zero();
  12671. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  12672. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  12673. this.radius = distance * 0.5;
  12674. this.centerWorld = BABYLON.Vector3.Zero();
  12675. this._update(BABYLON.Matrix.Identity());
  12676. }
  12677. // Methods
  12678. BoundingSphere.prototype._update = function (world) {
  12679. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  12680. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  12681. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  12682. };
  12683. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  12684. for (var i = 0; i < 6; i++) {
  12685. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  12686. return false;
  12687. }
  12688. return true;
  12689. };
  12690. BoundingSphere.prototype.intersectsPoint = function (point) {
  12691. var x = this.centerWorld.x - point.x;
  12692. var y = this.centerWorld.y - point.y;
  12693. var z = this.centerWorld.z - point.z;
  12694. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12695. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  12696. return false;
  12697. return true;
  12698. };
  12699. // Statics
  12700. BoundingSphere.Intersects = function (sphere0, sphere1) {
  12701. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  12702. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  12703. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  12704. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12705. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  12706. return false;
  12707. return true;
  12708. };
  12709. return BoundingSphere;
  12710. }());
  12711. BABYLON.BoundingSphere = BoundingSphere;
  12712. })(BABYLON || (BABYLON = {}));
  12713. //# sourceMappingURL=babylon.boundingSphere.js.map
  12714. var BABYLON;
  12715. (function (BABYLON) {
  12716. var BoundingBox = /** @class */ (function () {
  12717. function BoundingBox(minimum, maximum) {
  12718. this.minimum = minimum;
  12719. this.maximum = maximum;
  12720. this.vectors = new Array();
  12721. this.vectorsWorld = new Array();
  12722. // Bounding vectors
  12723. this.vectors.push(this.minimum.clone());
  12724. this.vectors.push(this.maximum.clone());
  12725. this.vectors.push(this.minimum.clone());
  12726. this.vectors[2].x = this.maximum.x;
  12727. this.vectors.push(this.minimum.clone());
  12728. this.vectors[3].y = this.maximum.y;
  12729. this.vectors.push(this.minimum.clone());
  12730. this.vectors[4].z = this.maximum.z;
  12731. this.vectors.push(this.maximum.clone());
  12732. this.vectors[5].z = this.minimum.z;
  12733. this.vectors.push(this.maximum.clone());
  12734. this.vectors[6].x = this.minimum.x;
  12735. this.vectors.push(this.maximum.clone());
  12736. this.vectors[7].y = this.minimum.y;
  12737. // OBB
  12738. this.center = this.maximum.add(this.minimum).scale(0.5);
  12739. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  12740. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  12741. // World
  12742. for (var index = 0; index < this.vectors.length; index++) {
  12743. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  12744. }
  12745. this.minimumWorld = BABYLON.Vector3.Zero();
  12746. this.maximumWorld = BABYLON.Vector3.Zero();
  12747. this.centerWorld = BABYLON.Vector3.Zero();
  12748. this.extendSizeWorld = BABYLON.Vector3.Zero();
  12749. this._update(BABYLON.Matrix.Identity());
  12750. }
  12751. // Methods
  12752. BoundingBox.prototype.getWorldMatrix = function () {
  12753. return this._worldMatrix;
  12754. };
  12755. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  12756. this._worldMatrix.copyFrom(matrix);
  12757. return this;
  12758. };
  12759. BoundingBox.prototype._update = function (world) {
  12760. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  12761. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  12762. for (var index = 0; index < this.vectors.length; index++) {
  12763. var v = this.vectorsWorld[index];
  12764. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  12765. if (v.x < this.minimumWorld.x)
  12766. this.minimumWorld.x = v.x;
  12767. if (v.y < this.minimumWorld.y)
  12768. this.minimumWorld.y = v.y;
  12769. if (v.z < this.minimumWorld.z)
  12770. this.minimumWorld.z = v.z;
  12771. if (v.x > this.maximumWorld.x)
  12772. this.maximumWorld.x = v.x;
  12773. if (v.y > this.maximumWorld.y)
  12774. this.maximumWorld.y = v.y;
  12775. if (v.z > this.maximumWorld.z)
  12776. this.maximumWorld.z = v.z;
  12777. }
  12778. // Extend
  12779. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  12780. this.extendSizeWorld.scaleInPlace(0.5);
  12781. // OBB
  12782. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  12783. this.centerWorld.scaleInPlace(0.5);
  12784. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  12785. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  12786. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  12787. this._worldMatrix = world;
  12788. };
  12789. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  12790. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  12791. };
  12792. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12793. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  12794. };
  12795. BoundingBox.prototype.intersectsPoint = function (point) {
  12796. var delta = -BABYLON.Epsilon;
  12797. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  12798. return false;
  12799. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  12800. return false;
  12801. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  12802. return false;
  12803. return true;
  12804. };
  12805. BoundingBox.prototype.intersectsSphere = function (sphere) {
  12806. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  12807. };
  12808. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  12809. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  12810. return false;
  12811. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  12812. return false;
  12813. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  12814. return false;
  12815. return true;
  12816. };
  12817. // Statics
  12818. BoundingBox.Intersects = function (box0, box1) {
  12819. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  12820. return false;
  12821. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  12822. return false;
  12823. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  12824. return false;
  12825. return true;
  12826. };
  12827. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  12828. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  12829. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  12830. return (num <= (sphereRadius * sphereRadius));
  12831. };
  12832. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  12833. for (var p = 0; p < 6; p++) {
  12834. for (var i = 0; i < 8; i++) {
  12835. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12836. return false;
  12837. }
  12838. }
  12839. }
  12840. return true;
  12841. };
  12842. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  12843. for (var p = 0; p < 6; p++) {
  12844. var inCount = 8;
  12845. for (var i = 0; i < 8; i++) {
  12846. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12847. --inCount;
  12848. }
  12849. else {
  12850. break;
  12851. }
  12852. }
  12853. if (inCount === 0)
  12854. return false;
  12855. }
  12856. return true;
  12857. };
  12858. return BoundingBox;
  12859. }());
  12860. BABYLON.BoundingBox = BoundingBox;
  12861. })(BABYLON || (BABYLON = {}));
  12862. //# sourceMappingURL=babylon.boundingBox.js.map
  12863. var BABYLON;
  12864. (function (BABYLON) {
  12865. var computeBoxExtents = function (axis, box) {
  12866. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  12867. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  12868. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  12869. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  12870. var r = r0 + r1 + r2;
  12871. return {
  12872. min: p - r,
  12873. max: p + r
  12874. };
  12875. };
  12876. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  12877. var axisOverlap = function (axis, box0, box1) {
  12878. var result0 = computeBoxExtents(axis, box0);
  12879. var result1 = computeBoxExtents(axis, box1);
  12880. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  12881. };
  12882. var BoundingInfo = /** @class */ (function () {
  12883. function BoundingInfo(minimum, maximum) {
  12884. this.minimum = minimum;
  12885. this.maximum = maximum;
  12886. this._isLocked = false;
  12887. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  12888. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  12889. }
  12890. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  12891. get: function () {
  12892. return this._isLocked;
  12893. },
  12894. set: function (value) {
  12895. this._isLocked = value;
  12896. },
  12897. enumerable: true,
  12898. configurable: true
  12899. });
  12900. // Methods
  12901. BoundingInfo.prototype.update = function (world) {
  12902. if (this._isLocked) {
  12903. return;
  12904. }
  12905. this.boundingBox._update(world);
  12906. this.boundingSphere._update(world);
  12907. };
  12908. /**
  12909. * Recreate the bounding info to be centered around a specific point given a specific extend.
  12910. * @param center New center of the bounding info
  12911. * @param extend New extend of the bounding info
  12912. */
  12913. BoundingInfo.prototype.centerOn = function (center, extend) {
  12914. this.minimum = center.subtract(extend);
  12915. this.maximum = center.add(extend);
  12916. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  12917. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  12918. return this;
  12919. };
  12920. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  12921. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  12922. return false;
  12923. return this.boundingBox.isInFrustum(frustumPlanes);
  12924. };
  12925. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  12926. /**
  12927. * Gets the world distance between the min and max points of the bounding box
  12928. */
  12929. get: function () {
  12930. var boundingBox = this.boundingBox;
  12931. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  12932. return size.length();
  12933. },
  12934. enumerable: true,
  12935. configurable: true
  12936. });
  12937. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12938. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  12939. };
  12940. BoundingInfo.prototype._checkCollision = function (collider) {
  12941. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  12942. };
  12943. BoundingInfo.prototype.intersectsPoint = function (point) {
  12944. if (!this.boundingSphere.centerWorld) {
  12945. return false;
  12946. }
  12947. if (!this.boundingSphere.intersectsPoint(point)) {
  12948. return false;
  12949. }
  12950. if (!this.boundingBox.intersectsPoint(point)) {
  12951. return false;
  12952. }
  12953. return true;
  12954. };
  12955. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  12956. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  12957. return false;
  12958. }
  12959. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  12960. return false;
  12961. }
  12962. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  12963. return false;
  12964. }
  12965. if (!precise) {
  12966. return true;
  12967. }
  12968. var box0 = this.boundingBox;
  12969. var box1 = boundingInfo.boundingBox;
  12970. if (!axisOverlap(box0.directions[0], box0, box1))
  12971. return false;
  12972. if (!axisOverlap(box0.directions[1], box0, box1))
  12973. return false;
  12974. if (!axisOverlap(box0.directions[2], box0, box1))
  12975. return false;
  12976. if (!axisOverlap(box1.directions[0], box0, box1))
  12977. return false;
  12978. if (!axisOverlap(box1.directions[1], box0, box1))
  12979. return false;
  12980. if (!axisOverlap(box1.directions[2], box0, box1))
  12981. return false;
  12982. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  12983. return false;
  12984. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  12985. return false;
  12986. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  12987. return false;
  12988. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  12989. return false;
  12990. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  12991. return false;
  12992. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  12993. return false;
  12994. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  12995. return false;
  12996. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  12997. return false;
  12998. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  12999. return false;
  13000. return true;
  13001. };
  13002. return BoundingInfo;
  13003. }());
  13004. BABYLON.BoundingInfo = BoundingInfo;
  13005. })(BABYLON || (BABYLON = {}));
  13006. //# sourceMappingURL=babylon.boundingInfo.js.map
  13007. var BABYLON;
  13008. (function (BABYLON) {
  13009. var TransformNode = /** @class */ (function (_super) {
  13010. __extends(TransformNode, _super);
  13011. function TransformNode(name, scene, isPure) {
  13012. if (scene === void 0) { scene = null; }
  13013. if (isPure === void 0) { isPure = true; }
  13014. var _this = _super.call(this, name, scene) || this;
  13015. // Properties
  13016. _this._rotation = BABYLON.Vector3.Zero();
  13017. _this._scaling = BABYLON.Vector3.One();
  13018. _this._isDirty = false;
  13019. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  13020. _this.scalingDeterminant = 1;
  13021. _this.infiniteDistance = false;
  13022. _this.position = BABYLON.Vector3.Zero();
  13023. _this._localWorld = BABYLON.Matrix.Zero();
  13024. _this._worldMatrix = BABYLON.Matrix.Zero();
  13025. _this._absolutePosition = BABYLON.Vector3.Zero();
  13026. _this._pivotMatrix = BABYLON.Matrix.Identity();
  13027. _this._postMultiplyPivotMatrix = false;
  13028. _this._isWorldMatrixFrozen = false;
  13029. /**
  13030. * An event triggered after the world matrix is updated
  13031. * @type {BABYLON.Observable}
  13032. */
  13033. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  13034. _this._nonUniformScaling = false;
  13035. if (isPure) {
  13036. _this.getScene().addTransformNode(_this);
  13037. }
  13038. return _this;
  13039. }
  13040. Object.defineProperty(TransformNode.prototype, "rotation", {
  13041. /**
  13042. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  13043. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  13044. * Default : (0.0, 0.0, 0.0)
  13045. */
  13046. get: function () {
  13047. return this._rotation;
  13048. },
  13049. set: function (newRotation) {
  13050. this._rotation = newRotation;
  13051. },
  13052. enumerable: true,
  13053. configurable: true
  13054. });
  13055. Object.defineProperty(TransformNode.prototype, "scaling", {
  13056. /**
  13057. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13058. * Default : (1.0, 1.0, 1.0)
  13059. */
  13060. get: function () {
  13061. return this._scaling;
  13062. },
  13063. /**
  13064. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13065. * Default : (1.0, 1.0, 1.0)
  13066. */
  13067. set: function (newScaling) {
  13068. this._scaling = newScaling;
  13069. },
  13070. enumerable: true,
  13071. configurable: true
  13072. });
  13073. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  13074. /**
  13075. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  13076. * It's null by default.
  13077. * 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)
  13078. */
  13079. get: function () {
  13080. return this._rotationQuaternion;
  13081. },
  13082. set: function (quaternion) {
  13083. this._rotationQuaternion = quaternion;
  13084. //reset the rotation vector.
  13085. if (quaternion && this.rotation.length()) {
  13086. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  13087. }
  13088. },
  13089. enumerable: true,
  13090. configurable: true
  13091. });
  13092. /**
  13093. * Returns the latest update of the World matrix
  13094. * Returns a Matrix.
  13095. */
  13096. TransformNode.prototype.getWorldMatrix = function () {
  13097. if (this._currentRenderId !== this.getScene().getRenderId()) {
  13098. this.computeWorldMatrix();
  13099. }
  13100. return this._worldMatrix;
  13101. };
  13102. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  13103. /**
  13104. * Returns directly the latest state of the mesh World matrix.
  13105. * A Matrix is returned.
  13106. */
  13107. get: function () {
  13108. return this._worldMatrix;
  13109. },
  13110. enumerable: true,
  13111. configurable: true
  13112. });
  13113. /**
  13114. * Copies the paramater passed Matrix into the mesh Pose matrix.
  13115. * Returns the AbstractMesh.
  13116. */
  13117. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  13118. this._poseMatrix.copyFrom(matrix);
  13119. return this;
  13120. };
  13121. /**
  13122. * Returns the mesh Pose matrix.
  13123. * Returned object : Matrix
  13124. */
  13125. TransformNode.prototype.getPoseMatrix = function () {
  13126. return this._poseMatrix;
  13127. };
  13128. TransformNode.prototype._isSynchronized = function () {
  13129. if (this._isDirty) {
  13130. return false;
  13131. }
  13132. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  13133. return false;
  13134. if (this._cache.pivotMatrixUpdated) {
  13135. return false;
  13136. }
  13137. if (this.infiniteDistance) {
  13138. return false;
  13139. }
  13140. if (!this._cache.position.equals(this.position))
  13141. return false;
  13142. if (this.rotationQuaternion) {
  13143. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13144. return false;
  13145. }
  13146. if (!this._cache.rotation.equals(this.rotation))
  13147. return false;
  13148. if (!this._cache.scaling.equals(this.scaling))
  13149. return false;
  13150. return true;
  13151. };
  13152. TransformNode.prototype._initCache = function () {
  13153. _super.prototype._initCache.call(this);
  13154. this._cache.localMatrixUpdated = false;
  13155. this._cache.position = BABYLON.Vector3.Zero();
  13156. this._cache.scaling = BABYLON.Vector3.Zero();
  13157. this._cache.rotation = BABYLON.Vector3.Zero();
  13158. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13159. this._cache.billboardMode = -1;
  13160. };
  13161. TransformNode.prototype.markAsDirty = function (property) {
  13162. if (property === "rotation") {
  13163. this.rotationQuaternion = null;
  13164. }
  13165. this._currentRenderId = Number.MAX_VALUE;
  13166. this._isDirty = true;
  13167. return this;
  13168. };
  13169. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  13170. /**
  13171. * Returns the current mesh absolute position.
  13172. * Retuns a Vector3.
  13173. */
  13174. get: function () {
  13175. return this._absolutePosition;
  13176. },
  13177. enumerable: true,
  13178. configurable: true
  13179. });
  13180. /**
  13181. * Sets a new pivot matrix to the mesh.
  13182. * Returns the AbstractMesh.
  13183. */
  13184. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  13185. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  13186. this._pivotMatrix = matrix.clone();
  13187. this._cache.pivotMatrixUpdated = true;
  13188. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  13189. if (this._postMultiplyPivotMatrix) {
  13190. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  13191. }
  13192. return this;
  13193. };
  13194. /**
  13195. * Returns the mesh pivot matrix.
  13196. * Default : Identity.
  13197. * A Matrix is returned.
  13198. */
  13199. TransformNode.prototype.getPivotMatrix = function () {
  13200. return this._pivotMatrix;
  13201. };
  13202. /**
  13203. * Prevents the World matrix to be computed any longer.
  13204. * Returns the AbstractMesh.
  13205. */
  13206. TransformNode.prototype.freezeWorldMatrix = function () {
  13207. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  13208. this.computeWorldMatrix(true);
  13209. this._isWorldMatrixFrozen = true;
  13210. return this;
  13211. };
  13212. /**
  13213. * Allows back the World matrix computation.
  13214. * Returns the AbstractMesh.
  13215. */
  13216. TransformNode.prototype.unfreezeWorldMatrix = function () {
  13217. this._isWorldMatrixFrozen = false;
  13218. this.computeWorldMatrix(true);
  13219. return this;
  13220. };
  13221. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  13222. /**
  13223. * True if the World matrix has been frozen.
  13224. * Returns a boolean.
  13225. */
  13226. get: function () {
  13227. return this._isWorldMatrixFrozen;
  13228. },
  13229. enumerable: true,
  13230. configurable: true
  13231. });
  13232. /**
  13233. * Retuns the mesh absolute position in the World.
  13234. * Returns a Vector3.
  13235. */
  13236. TransformNode.prototype.getAbsolutePosition = function () {
  13237. this.computeWorldMatrix();
  13238. return this._absolutePosition;
  13239. };
  13240. /**
  13241. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13242. * Returns the AbstractMesh.
  13243. */
  13244. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  13245. if (!absolutePosition) {
  13246. return this;
  13247. }
  13248. var absolutePositionX;
  13249. var absolutePositionY;
  13250. var absolutePositionZ;
  13251. if (absolutePosition.x === undefined) {
  13252. if (arguments.length < 3) {
  13253. return this;
  13254. }
  13255. absolutePositionX = arguments[0];
  13256. absolutePositionY = arguments[1];
  13257. absolutePositionZ = arguments[2];
  13258. }
  13259. else {
  13260. absolutePositionX = absolutePosition.x;
  13261. absolutePositionY = absolutePosition.y;
  13262. absolutePositionZ = absolutePosition.z;
  13263. }
  13264. if (this.parent) {
  13265. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13266. invertParentWorldMatrix.invert();
  13267. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13268. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13269. }
  13270. else {
  13271. this.position.x = absolutePositionX;
  13272. this.position.y = absolutePositionY;
  13273. this.position.z = absolutePositionZ;
  13274. }
  13275. return this;
  13276. };
  13277. /**
  13278. * Sets the mesh position in its local space.
  13279. * Returns the AbstractMesh.
  13280. */
  13281. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  13282. this.computeWorldMatrix();
  13283. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13284. return this;
  13285. };
  13286. /**
  13287. * Returns the mesh position in the local space from the current World matrix values.
  13288. * Returns a new Vector3.
  13289. */
  13290. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  13291. this.computeWorldMatrix();
  13292. var invLocalWorldMatrix = this._localWorld.clone();
  13293. invLocalWorldMatrix.invert();
  13294. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13295. };
  13296. /**
  13297. * Translates the mesh along the passed Vector3 in its local space.
  13298. * Returns the AbstractMesh.
  13299. */
  13300. TransformNode.prototype.locallyTranslate = function (vector3) {
  13301. this.computeWorldMatrix(true);
  13302. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13303. return this;
  13304. };
  13305. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13306. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  13307. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  13308. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  13309. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  13310. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  13311. /// <returns>Mesh oriented towards targetMesh</returns>
  13312. if (yawCor === void 0) { yawCor = 0; }
  13313. if (pitchCor === void 0) { pitchCor = 0; }
  13314. if (rollCor === void 0) { rollCor = 0; }
  13315. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13316. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  13317. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13318. targetPoint.subtractToRef(pos, dv);
  13319. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13320. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13321. var pitch = Math.atan2(dv.y, len);
  13322. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  13323. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13324. return this;
  13325. };
  13326. /**
  13327. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13328. * This Vector3 is expressed in the World space.
  13329. */
  13330. TransformNode.prototype.getDirection = function (localAxis) {
  13331. var result = BABYLON.Vector3.Zero();
  13332. this.getDirectionToRef(localAxis, result);
  13333. return result;
  13334. };
  13335. /**
  13336. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13337. * localAxis is expressed in the mesh local space.
  13338. * result is computed in the Wordl space from the mesh World matrix.
  13339. * Returns the AbstractMesh.
  13340. */
  13341. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  13342. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13343. return this;
  13344. };
  13345. TransformNode.prototype.setPivotPoint = function (point, space) {
  13346. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13347. if (this.getScene().getRenderId() == 0) {
  13348. this.computeWorldMatrix(true);
  13349. }
  13350. var wm = this.getWorldMatrix();
  13351. if (space == BABYLON.Space.WORLD) {
  13352. var tmat = BABYLON.Tmp.Matrix[0];
  13353. wm.invertToRef(tmat);
  13354. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13355. }
  13356. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13357. this._pivotMatrix.m[12] = -point.x;
  13358. this._pivotMatrix.m[13] = -point.y;
  13359. this._pivotMatrix.m[14] = -point.z;
  13360. this._cache.pivotMatrixUpdated = true;
  13361. return this;
  13362. };
  13363. /**
  13364. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13365. */
  13366. TransformNode.prototype.getPivotPoint = function () {
  13367. var point = BABYLON.Vector3.Zero();
  13368. this.getPivotPointToRef(point);
  13369. return point;
  13370. };
  13371. /**
  13372. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13373. * Returns the AbstractMesh.
  13374. */
  13375. TransformNode.prototype.getPivotPointToRef = function (result) {
  13376. result.x = -this._pivotMatrix.m[12];
  13377. result.y = -this._pivotMatrix.m[13];
  13378. result.z = -this._pivotMatrix.m[14];
  13379. return this;
  13380. };
  13381. /**
  13382. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13383. */
  13384. TransformNode.prototype.getAbsolutePivotPoint = function () {
  13385. var point = BABYLON.Vector3.Zero();
  13386. this.getAbsolutePivotPointToRef(point);
  13387. return point;
  13388. };
  13389. /**
  13390. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13391. * Returns the AbstractMesh.
  13392. */
  13393. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  13394. result.x = this._pivotMatrix.m[12];
  13395. result.y = this._pivotMatrix.m[13];
  13396. result.z = this._pivotMatrix.m[14];
  13397. this.getPivotPointToRef(result);
  13398. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13399. return this;
  13400. };
  13401. /**
  13402. * Defines the passed mesh as the parent of the current mesh.
  13403. * Returns the AbstractMesh.
  13404. */
  13405. TransformNode.prototype.setParent = function (mesh) {
  13406. var parent = mesh;
  13407. if (mesh == null) {
  13408. var rotation = BABYLON.Tmp.Quaternion[0];
  13409. var position = BABYLON.Tmp.Vector3[0];
  13410. var scale = BABYLON.Tmp.Vector3[1];
  13411. this.getWorldMatrix().decompose(scale, rotation, position);
  13412. if (this.rotationQuaternion) {
  13413. this.rotationQuaternion.copyFrom(rotation);
  13414. }
  13415. else {
  13416. rotation.toEulerAnglesToRef(this.rotation);
  13417. }
  13418. this.position.x = position.x;
  13419. this.position.y = position.y;
  13420. this.position.z = position.z;
  13421. }
  13422. else {
  13423. var position = BABYLON.Tmp.Vector3[0];
  13424. var m1 = BABYLON.Tmp.Matrix[0];
  13425. parent.getWorldMatrix().invertToRef(m1);
  13426. BABYLON.Vector3.TransformCoordinatesToRef(this.position, m1, position);
  13427. this.position.copyFrom(position);
  13428. }
  13429. this.parent = parent;
  13430. return this;
  13431. };
  13432. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  13433. get: function () {
  13434. return this._nonUniformScaling;
  13435. },
  13436. enumerable: true,
  13437. configurable: true
  13438. });
  13439. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  13440. if (this._nonUniformScaling === value) {
  13441. return false;
  13442. }
  13443. this._nonUniformScaling = true;
  13444. return true;
  13445. };
  13446. /**
  13447. * Attach the current TransformNode to another TransformNode associated with a bone
  13448. * @param bone Bone affecting the TransformNode
  13449. * @param affectedTransformNode TransformNode associated with the bone
  13450. */
  13451. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  13452. this._transformToBoneReferal = affectedTransformNode;
  13453. this.parent = bone;
  13454. if (bone.getWorldMatrix().determinant() < 0) {
  13455. this.scalingDeterminant *= -1;
  13456. }
  13457. return this;
  13458. };
  13459. TransformNode.prototype.detachFromBone = function () {
  13460. if (!this.parent) {
  13461. return this;
  13462. }
  13463. if (this.parent.getWorldMatrix().determinant() < 0) {
  13464. this.scalingDeterminant *= -1;
  13465. }
  13466. this._transformToBoneReferal = null;
  13467. this.parent = null;
  13468. return this;
  13469. };
  13470. /**
  13471. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  13472. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13473. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13474. * The passed axis is also normalized.
  13475. * Returns the AbstractMesh.
  13476. */
  13477. TransformNode.prototype.rotate = function (axis, amount, space) {
  13478. axis.normalize();
  13479. if (!this.rotationQuaternion) {
  13480. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13481. this.rotation = BABYLON.Vector3.Zero();
  13482. }
  13483. var rotationQuaternion;
  13484. if (!space || space === BABYLON.Space.LOCAL) {
  13485. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  13486. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  13487. }
  13488. else {
  13489. if (this.parent) {
  13490. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13491. invertParentWorldMatrix.invert();
  13492. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  13493. }
  13494. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  13495. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13496. }
  13497. return this;
  13498. };
  13499. /**
  13500. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  13501. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13502. * The passed axis is also normalized.
  13503. * Returns the AbstractMesh.
  13504. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  13505. */
  13506. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  13507. axis.normalize();
  13508. if (!this.rotationQuaternion) {
  13509. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13510. this.rotation.copyFromFloats(0, 0, 0);
  13511. }
  13512. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  13513. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  13514. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  13515. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  13516. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  13517. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  13518. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  13519. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  13520. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13521. return this;
  13522. };
  13523. /**
  13524. * Translates the mesh along the axis vector for the passed distance in the given space.
  13525. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13526. * Returns the AbstractMesh.
  13527. */
  13528. TransformNode.prototype.translate = function (axis, distance, space) {
  13529. var displacementVector = axis.scale(distance);
  13530. if (!space || space === BABYLON.Space.LOCAL) {
  13531. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13532. this.setPositionWithLocalVector(tempV3);
  13533. }
  13534. else {
  13535. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13536. }
  13537. return this;
  13538. };
  13539. /**
  13540. * Adds a rotation step to the mesh current rotation.
  13541. * x, y, z are Euler angles expressed in radians.
  13542. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13543. * This means this rotation is made in the mesh local space only.
  13544. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13545. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13546. * ```javascript
  13547. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13548. * ```
  13549. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13550. * 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.
  13551. * Returns the AbstractMesh.
  13552. */
  13553. TransformNode.prototype.addRotation = function (x, y, z) {
  13554. var rotationQuaternion;
  13555. if (this.rotationQuaternion) {
  13556. rotationQuaternion = this.rotationQuaternion;
  13557. }
  13558. else {
  13559. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13560. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13561. }
  13562. var accumulation = BABYLON.Tmp.Quaternion[0];
  13563. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13564. rotationQuaternion.multiplyInPlace(accumulation);
  13565. if (!this.rotationQuaternion) {
  13566. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13567. }
  13568. return this;
  13569. };
  13570. /**
  13571. * Computes the mesh World matrix and returns it.
  13572. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  13573. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  13574. * If the parameter `force`is set to `true`, the actual computation is done.
  13575. * Returns the mesh World Matrix.
  13576. */
  13577. TransformNode.prototype.computeWorldMatrix = function (force) {
  13578. if (this._isWorldMatrixFrozen) {
  13579. return this._worldMatrix;
  13580. }
  13581. if (!force && this.isSynchronized(true)) {
  13582. return this._worldMatrix;
  13583. }
  13584. this._cache.position.copyFrom(this.position);
  13585. this._cache.scaling.copyFrom(this.scaling);
  13586. this._cache.pivotMatrixUpdated = false;
  13587. this._cache.billboardMode = this.billboardMode;
  13588. this._currentRenderId = this.getScene().getRenderId();
  13589. this._isDirty = false;
  13590. // Scaling
  13591. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13592. // Rotation
  13593. //rotate, if quaternion is set and rotation was used
  13594. if (this.rotationQuaternion) {
  13595. var len = this.rotation.length();
  13596. if (len) {
  13597. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13598. this.rotation.copyFromFloats(0, 0, 0);
  13599. }
  13600. }
  13601. if (this.rotationQuaternion) {
  13602. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13603. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13604. }
  13605. else {
  13606. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13607. this._cache.rotation.copyFrom(this.rotation);
  13608. }
  13609. // Translation
  13610. var camera = this.getScene().activeCamera;
  13611. if (this.infiniteDistance && !this.parent && camera) {
  13612. var cameraWorldMatrix = camera.getWorldMatrix();
  13613. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13614. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13615. }
  13616. else {
  13617. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13618. }
  13619. // Composing transformations
  13620. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13621. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13622. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13623. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  13624. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  13625. // Need to decompose each rotation here
  13626. var currentPosition = BABYLON.Tmp.Vector3[3];
  13627. if (this.parent && this.parent.getWorldMatrix) {
  13628. if (this._transformToBoneReferal) {
  13629. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13630. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13631. }
  13632. else {
  13633. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13634. }
  13635. }
  13636. else {
  13637. currentPosition.copyFrom(this.position);
  13638. }
  13639. currentPosition.subtractInPlace(camera.globalPosition);
  13640. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13641. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  13642. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13643. }
  13644. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  13645. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13646. }
  13647. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  13648. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13649. }
  13650. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13651. }
  13652. else {
  13653. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  13654. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13655. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13656. }
  13657. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13658. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13659. }
  13660. // Local world
  13661. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13662. // Parent
  13663. if (this.parent && this.parent.getWorldMatrix) {
  13664. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  13665. if (this._transformToBoneReferal) {
  13666. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13667. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13668. }
  13669. else {
  13670. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13671. }
  13672. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13673. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13674. this._worldMatrix.copyFrom(this._localWorld);
  13675. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13676. }
  13677. else {
  13678. if (this._transformToBoneReferal) {
  13679. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13680. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13681. }
  13682. else {
  13683. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13684. }
  13685. }
  13686. this._markSyncedWithParent();
  13687. }
  13688. else {
  13689. this._worldMatrix.copyFrom(this._localWorld);
  13690. }
  13691. // Post multiply inverse of pivotMatrix
  13692. if (this._postMultiplyPivotMatrix) {
  13693. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  13694. }
  13695. // Normal matrix
  13696. if (this.scaling.isNonUniform) {
  13697. this._updateNonUniformScalingState(true);
  13698. }
  13699. else if (this.parent && this.parent._nonUniformScaling) {
  13700. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  13701. }
  13702. else {
  13703. this._updateNonUniformScalingState(false);
  13704. }
  13705. this._afterComputeWorldMatrix();
  13706. // Absolute position
  13707. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  13708. // Callbacks
  13709. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  13710. if (!this._poseMatrix) {
  13711. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  13712. }
  13713. return this._worldMatrix;
  13714. };
  13715. TransformNode.prototype._afterComputeWorldMatrix = function () {
  13716. };
  13717. /**
  13718. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  13719. * @param func: callback function to add
  13720. *
  13721. * Returns the TransformNode.
  13722. */
  13723. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  13724. this.onAfterWorldMatrixUpdateObservable.add(func);
  13725. return this;
  13726. };
  13727. /**
  13728. * Removes a registered callback function.
  13729. * Returns the TransformNode.
  13730. */
  13731. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  13732. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  13733. return this;
  13734. };
  13735. TransformNode.prototype.clone = function (name, newParent) {
  13736. var _this = this;
  13737. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  13738. result.name = name;
  13739. result.id = name;
  13740. if (newParent) {
  13741. result.parent = newParent;
  13742. }
  13743. return result;
  13744. };
  13745. TransformNode.prototype.serialize = function (serializationObject) {
  13746. if (serializationObject === void 0) { serializationObject = null; }
  13747. if (!serializationObject) {
  13748. serializationObject = {};
  13749. }
  13750. serializationObject.name = this.name;
  13751. serializationObject.id = this.id;
  13752. serializationObject.type = this.getClassName();
  13753. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  13754. serializationObject.tags = BABYLON.Tags.GetTags(this);
  13755. }
  13756. serializationObject.position = this.position.asArray();
  13757. if (this.rotationQuaternion) {
  13758. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  13759. }
  13760. else if (this.rotation) {
  13761. serializationObject.rotation = this.rotation.asArray();
  13762. }
  13763. serializationObject.scaling = this.scaling.asArray();
  13764. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  13765. serializationObject.isEnabled = this.isEnabled();
  13766. serializationObject.infiniteDistance = this.infiniteDistance;
  13767. serializationObject.billboardMode = this.billboardMode;
  13768. // Parent
  13769. if (this.parent) {
  13770. serializationObject.parentId = this.parent.id;
  13771. }
  13772. // Metadata
  13773. if (this.metadata) {
  13774. serializationObject.metadata = this.metadata;
  13775. }
  13776. return serializationObject;
  13777. };
  13778. // Statics
  13779. /**
  13780. * Returns a new TransformNode object parsed from the source provided.
  13781. * The parameter `parsedMesh` is the source.
  13782. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  13783. */
  13784. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  13785. var transformNode = new TransformNode(parsedTransformNode.name, scene);
  13786. transformNode.id = parsedTransformNode.id;
  13787. if (BABYLON.Tags) {
  13788. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  13789. }
  13790. transformNode.position = BABYLON.Vector3.FromArray(parsedTransformNode.position);
  13791. if (parsedTransformNode.metadata !== undefined) {
  13792. transformNode.metadata = parsedTransformNode.metadata;
  13793. }
  13794. if (parsedTransformNode.rotationQuaternion) {
  13795. transformNode.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedTransformNode.rotationQuaternion);
  13796. }
  13797. else if (parsedTransformNode.rotation) {
  13798. transformNode.rotation = BABYLON.Vector3.FromArray(parsedTransformNode.rotation);
  13799. }
  13800. transformNode.scaling = BABYLON.Vector3.FromArray(parsedTransformNode.scaling);
  13801. if (parsedTransformNode.localMatrix) {
  13802. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  13803. }
  13804. else if (parsedTransformNode.pivotMatrix) {
  13805. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  13806. }
  13807. transformNode.setEnabled(parsedTransformNode.isEnabled);
  13808. transformNode.infiniteDistance = parsedTransformNode.infiniteDistance;
  13809. transformNode.billboardMode = parsedTransformNode.billboardMode;
  13810. // Parent
  13811. if (parsedTransformNode.parentId) {
  13812. transformNode._waitingParentId = parsedTransformNode.parentId;
  13813. }
  13814. return transformNode;
  13815. };
  13816. /**
  13817. * Disposes the TransformNode.
  13818. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13819. * Returns nothing.
  13820. */
  13821. TransformNode.prototype.dispose = function (doNotRecurse) {
  13822. // Animations
  13823. this.getScene().stopAnimation(this);
  13824. // Remove from scene
  13825. this.getScene().removeTransformNode(this);
  13826. this._cache = null;
  13827. if (!doNotRecurse) {
  13828. // Children
  13829. var objects = this.getDescendants(true);
  13830. for (var index = 0; index < objects.length; index++) {
  13831. objects[index].dispose();
  13832. }
  13833. }
  13834. else {
  13835. var childMeshes = this.getChildMeshes(true);
  13836. for (index = 0; index < childMeshes.length; index++) {
  13837. var child = childMeshes[index];
  13838. child.parent = null;
  13839. child.computeWorldMatrix(true);
  13840. }
  13841. }
  13842. this.onAfterWorldMatrixUpdateObservable.clear();
  13843. _super.prototype.dispose.call(this);
  13844. };
  13845. // Statics
  13846. TransformNode.BILLBOARDMODE_NONE = 0;
  13847. TransformNode.BILLBOARDMODE_X = 1;
  13848. TransformNode.BILLBOARDMODE_Y = 2;
  13849. TransformNode.BILLBOARDMODE_Z = 4;
  13850. TransformNode.BILLBOARDMODE_ALL = 7;
  13851. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13852. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  13853. return TransformNode;
  13854. }(BABYLON.Node));
  13855. BABYLON.TransformNode = TransformNode;
  13856. })(BABYLON || (BABYLON = {}));
  13857. //# sourceMappingURL=babylon.transformNode.js.map
  13858. var BABYLON;
  13859. (function (BABYLON) {
  13860. var AbstractMesh = /** @class */ (function (_super) {
  13861. __extends(AbstractMesh, _super);
  13862. // Constructor
  13863. function AbstractMesh(name, scene) {
  13864. if (scene === void 0) { scene = null; }
  13865. var _this = _super.call(this, name, scene, false) || this;
  13866. _this._facetNb = 0; // facet number
  13867. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  13868. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  13869. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  13870. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  13871. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  13872. _this._subDiv = {
  13873. max: 1,
  13874. X: 1,
  13875. Y: 1,
  13876. Z: 1
  13877. };
  13878. _this._facetDepthSort = false; // is the facet depth sort to be computed
  13879. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  13880. // Events
  13881. /**
  13882. * An event triggered when this mesh collides with another one
  13883. * @type {BABYLON.Observable}
  13884. */
  13885. _this.onCollideObservable = new BABYLON.Observable();
  13886. /**
  13887. * An event triggered when the collision's position changes
  13888. * @type {BABYLON.Observable}
  13889. */
  13890. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  13891. /**
  13892. * An event triggered when material is changed
  13893. * @type {BABYLON.Observable}
  13894. */
  13895. _this.onMaterialChangedObservable = new BABYLON.Observable();
  13896. // Properties
  13897. _this.definedFacingForward = true; // orientation for POV movement & rotation
  13898. /**
  13899. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  13900. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  13901. * or
  13902. * 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.
  13903. * for more info check WebGl documentations
  13904. */
  13905. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  13906. /**
  13907. * 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:
  13908. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  13909. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  13910. * 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.
  13911. */
  13912. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  13913. /**
  13914. * 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.
  13915. * The default value is -1 which means don't break the query and wait till the result.
  13916. */
  13917. _this.occlusionRetryCount = -1;
  13918. _this._occlusionInternalRetryCounter = 0;
  13919. _this._isOccluded = false;
  13920. _this._isOcclusionQueryInProgress = false;
  13921. _this.visibility = 1.0;
  13922. _this.alphaIndex = Number.MAX_VALUE;
  13923. _this.isVisible = true;
  13924. _this.isPickable = true;
  13925. _this.showBoundingBox = false;
  13926. _this.showSubMeshesBoundingBox = false;
  13927. _this.isBlocker = false;
  13928. _this.enablePointerMoveEvents = false;
  13929. _this.renderingGroupId = 0;
  13930. _this._receiveShadows = false;
  13931. _this.renderOutline = false;
  13932. _this.outlineColor = BABYLON.Color3.Red();
  13933. _this.outlineWidth = 0.02;
  13934. _this.renderOverlay = false;
  13935. _this.overlayColor = BABYLON.Color3.Red();
  13936. _this.overlayAlpha = 0.5;
  13937. _this._hasVertexAlpha = false;
  13938. _this._useVertexColors = true;
  13939. _this._computeBonesUsingShaders = true;
  13940. _this._numBoneInfluencers = 4;
  13941. _this._applyFog = true;
  13942. _this.useOctreeForRenderingSelection = true;
  13943. _this.useOctreeForPicking = true;
  13944. _this.useOctreeForCollisions = true;
  13945. _this._layerMask = 0x0FFFFFFF;
  13946. /**
  13947. * True if the mesh must be rendered in any case.
  13948. */
  13949. _this.alwaysSelectAsActiveMesh = false;
  13950. // Collisions
  13951. _this._checkCollisions = false;
  13952. _this._collisionMask = -1;
  13953. _this._collisionGroup = -1;
  13954. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  13955. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  13956. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  13957. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  13958. // Edges
  13959. _this.edgesWidth = 1;
  13960. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  13961. // Cache
  13962. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  13963. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  13964. _this._isDisposed = false;
  13965. _this._renderId = 0;
  13966. _this._intersectionsInProgress = new Array();
  13967. _this._unIndexed = false;
  13968. _this._lightSources = new Array();
  13969. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  13970. if (collidedMesh === void 0) { collidedMesh = null; }
  13971. //TODO move this to the collision coordinator!
  13972. if (_this.getScene().workerCollisions)
  13973. newPosition.multiplyInPlace(_this._collider.radius);
  13974. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  13975. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  13976. _this.position.addInPlace(_this._diffPositionForCollisions);
  13977. }
  13978. if (collidedMesh) {
  13979. _this.onCollideObservable.notifyObservers(collidedMesh);
  13980. }
  13981. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  13982. };
  13983. _this.getScene().addMesh(_this);
  13984. _this._resyncLightSources();
  13985. return _this;
  13986. }
  13987. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  13988. get: function () {
  13989. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  13990. },
  13991. enumerable: true,
  13992. configurable: true
  13993. });
  13994. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  13995. get: function () {
  13996. return BABYLON.TransformNode.BILLBOARDMODE_X;
  13997. },
  13998. enumerable: true,
  13999. configurable: true
  14000. });
  14001. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  14002. get: function () {
  14003. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  14004. },
  14005. enumerable: true,
  14006. configurable: true
  14007. });
  14008. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  14009. get: function () {
  14010. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  14011. },
  14012. enumerable: true,
  14013. configurable: true
  14014. });
  14015. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  14016. get: function () {
  14017. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  14018. },
  14019. enumerable: true,
  14020. configurable: true
  14021. });
  14022. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  14023. /**
  14024. * Read-only : the number of facets in the mesh
  14025. */
  14026. get: function () {
  14027. return this._facetNb;
  14028. },
  14029. enumerable: true,
  14030. configurable: true
  14031. });
  14032. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  14033. /**
  14034. * The number (integer) of subdivisions per axis in the partioning space
  14035. */
  14036. get: function () {
  14037. return this._partitioningSubdivisions;
  14038. },
  14039. set: function (nb) {
  14040. this._partitioningSubdivisions = nb;
  14041. },
  14042. enumerable: true,
  14043. configurable: true
  14044. });
  14045. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  14046. /**
  14047. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  14048. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  14049. */
  14050. get: function () {
  14051. return this._partitioningBBoxRatio;
  14052. },
  14053. set: function (ratio) {
  14054. this._partitioningBBoxRatio = ratio;
  14055. },
  14056. enumerable: true,
  14057. configurable: true
  14058. });
  14059. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  14060. /**
  14061. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  14062. * Works only for updatable meshes.
  14063. * Doesn't work with multi-materials.
  14064. */
  14065. get: function () {
  14066. return this._facetDepthSort;
  14067. },
  14068. set: function (sort) {
  14069. this._facetDepthSort = sort;
  14070. },
  14071. enumerable: true,
  14072. configurable: true
  14073. });
  14074. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  14075. /**
  14076. * The location (Vector3) where the facet depth sort must be computed from.
  14077. * By default, the active camera position.
  14078. * Used only when facet depth sort is enabled.
  14079. */
  14080. get: function () {
  14081. return this._facetDepthSortFrom;
  14082. },
  14083. set: function (location) {
  14084. this._facetDepthSortFrom = location;
  14085. },
  14086. enumerable: true,
  14087. configurable: true
  14088. });
  14089. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  14090. /**
  14091. * Read-only boolean : is the feature facetData enabled ?
  14092. */
  14093. get: function () {
  14094. return this._facetDataEnabled;
  14095. },
  14096. enumerable: true,
  14097. configurable: true
  14098. });
  14099. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  14100. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  14101. return false;
  14102. }
  14103. this._markSubMeshesAsMiscDirty();
  14104. return true;
  14105. };
  14106. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  14107. set: function (callback) {
  14108. if (this._onCollideObserver) {
  14109. this.onCollideObservable.remove(this._onCollideObserver);
  14110. }
  14111. this._onCollideObserver = this.onCollideObservable.add(callback);
  14112. },
  14113. enumerable: true,
  14114. configurable: true
  14115. });
  14116. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  14117. set: function (callback) {
  14118. if (this._onCollisionPositionChangeObserver) {
  14119. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  14120. }
  14121. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  14122. },
  14123. enumerable: true,
  14124. configurable: true
  14125. });
  14126. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  14127. /**
  14128. * 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.
  14129. */
  14130. get: function () {
  14131. return this._isOccluded;
  14132. },
  14133. set: function (value) {
  14134. this._isOccluded = value;
  14135. },
  14136. enumerable: true,
  14137. configurable: true
  14138. });
  14139. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  14140. /**
  14141. * Flag to check the progress status of the query
  14142. */
  14143. get: function () {
  14144. return this._isOcclusionQueryInProgress;
  14145. },
  14146. enumerable: true,
  14147. configurable: true
  14148. });
  14149. Object.defineProperty(AbstractMesh.prototype, "material", {
  14150. get: function () {
  14151. return this._material;
  14152. },
  14153. set: function (value) {
  14154. if (this._material === value) {
  14155. return;
  14156. }
  14157. this._material = value;
  14158. if (this.onMaterialChangedObservable.hasObservers) {
  14159. this.onMaterialChangedObservable.notifyObservers(this);
  14160. }
  14161. if (!this.subMeshes) {
  14162. return;
  14163. }
  14164. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14165. var subMesh = _a[_i];
  14166. subMesh.setEffect(null);
  14167. }
  14168. },
  14169. enumerable: true,
  14170. configurable: true
  14171. });
  14172. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  14173. get: function () {
  14174. return this._receiveShadows;
  14175. },
  14176. set: function (value) {
  14177. if (this._receiveShadows === value) {
  14178. return;
  14179. }
  14180. this._receiveShadows = value;
  14181. this._markSubMeshesAsLightDirty();
  14182. },
  14183. enumerable: true,
  14184. configurable: true
  14185. });
  14186. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  14187. get: function () {
  14188. return this._hasVertexAlpha;
  14189. },
  14190. set: function (value) {
  14191. if (this._hasVertexAlpha === value) {
  14192. return;
  14193. }
  14194. this._hasVertexAlpha = value;
  14195. this._markSubMeshesAsAttributesDirty();
  14196. },
  14197. enumerable: true,
  14198. configurable: true
  14199. });
  14200. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  14201. get: function () {
  14202. return this._useVertexColors;
  14203. },
  14204. set: function (value) {
  14205. if (this._useVertexColors === value) {
  14206. return;
  14207. }
  14208. this._useVertexColors = value;
  14209. this._markSubMeshesAsAttributesDirty();
  14210. },
  14211. enumerable: true,
  14212. configurable: true
  14213. });
  14214. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  14215. get: function () {
  14216. return this._computeBonesUsingShaders;
  14217. },
  14218. set: function (value) {
  14219. if (this._computeBonesUsingShaders === value) {
  14220. return;
  14221. }
  14222. this._computeBonesUsingShaders = value;
  14223. this._markSubMeshesAsAttributesDirty();
  14224. },
  14225. enumerable: true,
  14226. configurable: true
  14227. });
  14228. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  14229. get: function () {
  14230. return this._numBoneInfluencers;
  14231. },
  14232. set: function (value) {
  14233. if (this._numBoneInfluencers === value) {
  14234. return;
  14235. }
  14236. this._numBoneInfluencers = value;
  14237. this._markSubMeshesAsAttributesDirty();
  14238. },
  14239. enumerable: true,
  14240. configurable: true
  14241. });
  14242. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  14243. get: function () {
  14244. return this._applyFog;
  14245. },
  14246. set: function (value) {
  14247. if (this._applyFog === value) {
  14248. return;
  14249. }
  14250. this._applyFog = value;
  14251. this._markSubMeshesAsMiscDirty();
  14252. },
  14253. enumerable: true,
  14254. configurable: true
  14255. });
  14256. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  14257. get: function () {
  14258. return this._layerMask;
  14259. },
  14260. set: function (value) {
  14261. if (value === this._layerMask) {
  14262. return;
  14263. }
  14264. this._layerMask = value;
  14265. this._resyncLightSources();
  14266. },
  14267. enumerable: true,
  14268. configurable: true
  14269. });
  14270. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  14271. get: function () {
  14272. return this._collisionMask;
  14273. },
  14274. set: function (mask) {
  14275. this._collisionMask = !isNaN(mask) ? mask : -1;
  14276. },
  14277. enumerable: true,
  14278. configurable: true
  14279. });
  14280. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  14281. get: function () {
  14282. return this._collisionGroup;
  14283. },
  14284. set: function (mask) {
  14285. this._collisionGroup = !isNaN(mask) ? mask : -1;
  14286. },
  14287. enumerable: true,
  14288. configurable: true
  14289. });
  14290. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  14291. get: function () {
  14292. return null;
  14293. },
  14294. enumerable: true,
  14295. configurable: true
  14296. });
  14297. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  14298. get: function () {
  14299. return this._skeleton;
  14300. },
  14301. set: function (value) {
  14302. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  14303. this._skeleton._unregisterMeshWithPoseMatrix(this);
  14304. }
  14305. if (value && value.needInitialSkinMatrix) {
  14306. value._registerMeshWithPoseMatrix(this);
  14307. }
  14308. this._skeleton = value;
  14309. if (!this._skeleton) {
  14310. this._bonesTransformMatrices = null;
  14311. }
  14312. this._markSubMeshesAsAttributesDirty();
  14313. },
  14314. enumerable: true,
  14315. configurable: true
  14316. });
  14317. /**
  14318. * Boolean : true if the mesh has been disposed.
  14319. */
  14320. AbstractMesh.prototype.isDisposed = function () {
  14321. return this._isDisposed;
  14322. };
  14323. /**
  14324. * Returns the string "AbstractMesh"
  14325. */
  14326. AbstractMesh.prototype.getClassName = function () {
  14327. return "AbstractMesh";
  14328. };
  14329. /**
  14330. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14331. */
  14332. AbstractMesh.prototype.toString = function (fullDetails) {
  14333. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  14334. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  14335. if (this._skeleton) {
  14336. ret += ", skeleton: " + this._skeleton.name;
  14337. }
  14338. if (fullDetails) {
  14339. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  14340. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  14341. }
  14342. return ret;
  14343. };
  14344. AbstractMesh.prototype._rebuild = function () {
  14345. if (this._occlusionQuery) {
  14346. this._occlusionQuery = null;
  14347. }
  14348. if (this._edgesRenderer) {
  14349. this._edgesRenderer._rebuild();
  14350. }
  14351. if (!this.subMeshes) {
  14352. return;
  14353. }
  14354. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14355. var subMesh = _a[_i];
  14356. subMesh._rebuild();
  14357. }
  14358. };
  14359. AbstractMesh.prototype._resyncLightSources = function () {
  14360. this._lightSources.length = 0;
  14361. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  14362. var light = _a[_i];
  14363. if (!light.isEnabled()) {
  14364. continue;
  14365. }
  14366. if (light.canAffectMesh(this)) {
  14367. this._lightSources.push(light);
  14368. }
  14369. }
  14370. this._markSubMeshesAsLightDirty();
  14371. };
  14372. AbstractMesh.prototype._resyncLighSource = function (light) {
  14373. var isIn = light.isEnabled() && light.canAffectMesh(this);
  14374. var index = this._lightSources.indexOf(light);
  14375. if (index === -1) {
  14376. if (!isIn) {
  14377. return;
  14378. }
  14379. this._lightSources.push(light);
  14380. }
  14381. else {
  14382. if (isIn) {
  14383. return;
  14384. }
  14385. this._lightSources.splice(index, 1);
  14386. }
  14387. this._markSubMeshesAsLightDirty();
  14388. };
  14389. AbstractMesh.prototype._removeLightSource = function (light) {
  14390. var index = this._lightSources.indexOf(light);
  14391. if (index === -1) {
  14392. return;
  14393. }
  14394. this._lightSources.splice(index, 1);
  14395. };
  14396. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  14397. if (!this.subMeshes) {
  14398. return;
  14399. }
  14400. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14401. var subMesh = _a[_i];
  14402. if (subMesh._materialDefines) {
  14403. func(subMesh._materialDefines);
  14404. }
  14405. }
  14406. };
  14407. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  14408. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  14409. };
  14410. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  14411. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  14412. };
  14413. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  14414. if (!this.subMeshes) {
  14415. return;
  14416. }
  14417. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14418. var subMesh = _a[_i];
  14419. var material = subMesh.getMaterial();
  14420. if (material) {
  14421. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  14422. }
  14423. }
  14424. };
  14425. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  14426. /**
  14427. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14428. * Default : (1.0, 1.0, 1.0)
  14429. */
  14430. get: function () {
  14431. return this._scaling;
  14432. },
  14433. /**
  14434. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14435. * Default : (1.0, 1.0, 1.0)
  14436. */
  14437. set: function (newScaling) {
  14438. this._scaling = newScaling;
  14439. if (this.physicsImpostor) {
  14440. this.physicsImpostor.forceUpdate();
  14441. }
  14442. },
  14443. enumerable: true,
  14444. configurable: true
  14445. });
  14446. // Methods
  14447. /**
  14448. * Disables the mesh edger rendering mode.
  14449. * Returns the AbstractMesh.
  14450. */
  14451. AbstractMesh.prototype.disableEdgesRendering = function () {
  14452. if (this._edgesRenderer) {
  14453. this._edgesRenderer.dispose();
  14454. this._edgesRenderer = null;
  14455. }
  14456. return this;
  14457. };
  14458. /**
  14459. * Enables the edge rendering mode on the mesh.
  14460. * This mode makes the mesh edges visible.
  14461. * Returns the AbstractMesh.
  14462. */
  14463. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  14464. if (epsilon === void 0) { epsilon = 0.95; }
  14465. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  14466. this.disableEdgesRendering();
  14467. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  14468. return this;
  14469. };
  14470. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  14471. /**
  14472. * Returns true if the mesh is blocked. Used by the class Mesh.
  14473. * Returns the boolean `false` by default.
  14474. */
  14475. get: function () {
  14476. return false;
  14477. },
  14478. enumerable: true,
  14479. configurable: true
  14480. });
  14481. /**
  14482. * Returns the mesh itself by default, used by the class Mesh.
  14483. * Returned type : AbstractMesh
  14484. */
  14485. AbstractMesh.prototype.getLOD = function (camera) {
  14486. return this;
  14487. };
  14488. /**
  14489. * Returns 0 by default, used by the class Mesh.
  14490. * Returns an integer.
  14491. */
  14492. AbstractMesh.prototype.getTotalVertices = function () {
  14493. return 0;
  14494. };
  14495. /**
  14496. * Returns null by default, used by the class Mesh.
  14497. * Returned type : integer array
  14498. */
  14499. AbstractMesh.prototype.getIndices = function () {
  14500. return null;
  14501. };
  14502. /**
  14503. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  14504. * Returned type : float array or Float32Array
  14505. */
  14506. AbstractMesh.prototype.getVerticesData = function (kind) {
  14507. return null;
  14508. };
  14509. /**
  14510. * Sets the vertex data of the mesh geometry for the requested `kind`.
  14511. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  14512. * The `data` are either a numeric array either a Float32Array.
  14513. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  14514. * 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).
  14515. * Note that a new underlying VertexBuffer object is created each call.
  14516. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  14517. *
  14518. * Possible `kind` values :
  14519. * - BABYLON.VertexBuffer.PositionKind
  14520. * - BABYLON.VertexBuffer.UVKind
  14521. * - BABYLON.VertexBuffer.UV2Kind
  14522. * - BABYLON.VertexBuffer.UV3Kind
  14523. * - BABYLON.VertexBuffer.UV4Kind
  14524. * - BABYLON.VertexBuffer.UV5Kind
  14525. * - BABYLON.VertexBuffer.UV6Kind
  14526. * - BABYLON.VertexBuffer.ColorKind
  14527. * - BABYLON.VertexBuffer.MatricesIndicesKind
  14528. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  14529. * - BABYLON.VertexBuffer.MatricesWeightsKind
  14530. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  14531. *
  14532. * Returns the Mesh.
  14533. */
  14534. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14535. return this;
  14536. };
  14537. /**
  14538. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  14539. * If the mesh has no geometry, it is simply returned as it is.
  14540. * The `data` are either a numeric array either a Float32Array.
  14541. * No new underlying VertexBuffer object is created.
  14542. * 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.
  14543. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  14544. *
  14545. * Possible `kind` values :
  14546. * - BABYLON.VertexBuffer.PositionKind
  14547. * - BABYLON.VertexBuffer.UVKind
  14548. * - BABYLON.VertexBuffer.UV2Kind
  14549. * - BABYLON.VertexBuffer.UV3Kind
  14550. * - BABYLON.VertexBuffer.UV4Kind
  14551. * - BABYLON.VertexBuffer.UV5Kind
  14552. * - BABYLON.VertexBuffer.UV6Kind
  14553. * - BABYLON.VertexBuffer.ColorKind
  14554. * - BABYLON.VertexBuffer.MatricesIndicesKind
  14555. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  14556. * - BABYLON.VertexBuffer.MatricesWeightsKind
  14557. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  14558. *
  14559. * Returns the Mesh.
  14560. */
  14561. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14562. return this;
  14563. };
  14564. /**
  14565. * Sets the mesh indices.
  14566. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  14567. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  14568. * This method creates a new index buffer each call.
  14569. * Returns the Mesh.
  14570. */
  14571. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  14572. return this;
  14573. };
  14574. /** Returns false by default, used by the class Mesh.
  14575. * Returns a boolean
  14576. */
  14577. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  14578. return false;
  14579. };
  14580. /**
  14581. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  14582. * Returns a BoundingInfo
  14583. */
  14584. AbstractMesh.prototype.getBoundingInfo = function () {
  14585. if (this._masterMesh) {
  14586. return this._masterMesh.getBoundingInfo();
  14587. }
  14588. if (!this._boundingInfo) {
  14589. // this._boundingInfo is being created here
  14590. this._updateBoundingInfo();
  14591. }
  14592. // cannot be null.
  14593. return this._boundingInfo;
  14594. };
  14595. /**
  14596. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  14597. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  14598. */
  14599. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  14600. if (includeDescendants === void 0) { includeDescendants = true; }
  14601. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  14602. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  14603. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  14604. if (maxDimension === 0) {
  14605. return this;
  14606. }
  14607. var scale = 1 / maxDimension;
  14608. this.scaling.scaleInPlace(scale);
  14609. return this;
  14610. };
  14611. /**
  14612. * Sets a mesh new object BoundingInfo.
  14613. * Returns the AbstractMesh.
  14614. */
  14615. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  14616. this._boundingInfo = boundingInfo;
  14617. return this;
  14618. };
  14619. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  14620. get: function () {
  14621. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  14622. },
  14623. enumerable: true,
  14624. configurable: true
  14625. });
  14626. AbstractMesh.prototype._preActivate = function () {
  14627. };
  14628. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  14629. };
  14630. AbstractMesh.prototype._activate = function (renderId) {
  14631. this._renderId = renderId;
  14632. };
  14633. /**
  14634. * Returns the latest update of the World matrix
  14635. * Returns a Matrix.
  14636. */
  14637. AbstractMesh.prototype.getWorldMatrix = function () {
  14638. if (this._masterMesh) {
  14639. return this._masterMesh.getWorldMatrix();
  14640. }
  14641. return _super.prototype.getWorldMatrix.call(this);
  14642. };
  14643. // ================================== Point of View Movement =================================
  14644. /**
  14645. * Perform relative position change from the point of view of behind the front of the mesh.
  14646. * This is performed taking into account the meshes current rotation, so you do not have to care.
  14647. * Supports definition of mesh facing forward or backward.
  14648. * @param {number} amountRight
  14649. * @param {number} amountUp
  14650. * @param {number} amountForward
  14651. *
  14652. * Returns the AbstractMesh.
  14653. */
  14654. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  14655. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  14656. return this;
  14657. };
  14658. /**
  14659. * Calculate relative position change from the point of view of behind the front of the mesh.
  14660. * This is performed taking into account the meshes current rotation, so you do not have to care.
  14661. * Supports definition of mesh facing forward or backward.
  14662. * @param {number} amountRight
  14663. * @param {number} amountUp
  14664. * @param {number} amountForward
  14665. *
  14666. * Returns a new Vector3.
  14667. */
  14668. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  14669. var rotMatrix = new BABYLON.Matrix();
  14670. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14671. rotQuaternion.toRotationMatrix(rotMatrix);
  14672. var translationDelta = BABYLON.Vector3.Zero();
  14673. var defForwardMult = this.definedFacingForward ? -1 : 1;
  14674. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  14675. return translationDelta;
  14676. };
  14677. // ================================== Point of View Rotation =================================
  14678. /**
  14679. * Perform relative rotation change from the point of view of behind the front of the mesh.
  14680. * Supports definition of mesh facing forward or backward.
  14681. * @param {number} flipBack
  14682. * @param {number} twirlClockwise
  14683. * @param {number} tiltRight
  14684. *
  14685. * Returns the AbstractMesh.
  14686. */
  14687. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  14688. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  14689. return this;
  14690. };
  14691. /**
  14692. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  14693. * Supports definition of mesh facing forward or backward.
  14694. * @param {number} flipBack
  14695. * @param {number} twirlClockwise
  14696. * @param {number} tiltRight
  14697. *
  14698. * Returns a new Vector3.
  14699. */
  14700. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  14701. var defForwardMult = this.definedFacingForward ? 1 : -1;
  14702. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  14703. };
  14704. /**
  14705. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  14706. * @param includeDescendants Include bounding info from descendants as well (true by default).
  14707. */
  14708. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  14709. if (includeDescendants === void 0) { includeDescendants = true; }
  14710. this.computeWorldMatrix(true);
  14711. var min;
  14712. var max;
  14713. var boundingInfo = this.getBoundingInfo();
  14714. if (!this.subMeshes) {
  14715. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14716. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  14717. }
  14718. else {
  14719. min = boundingInfo.boundingBox.minimumWorld;
  14720. max = boundingInfo.boundingBox.maximumWorld;
  14721. }
  14722. if (includeDescendants) {
  14723. var descendants = this.getDescendants(false);
  14724. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  14725. var descendant = descendants_1[_i];
  14726. var childMesh = descendant;
  14727. childMesh.computeWorldMatrix(true);
  14728. var childBoundingInfo = childMesh.getBoundingInfo();
  14729. if (childMesh.getTotalVertices() === 0) {
  14730. continue;
  14731. }
  14732. var boundingBox = childBoundingInfo.boundingBox;
  14733. var minBox = boundingBox.minimumWorld;
  14734. var maxBox = boundingBox.maximumWorld;
  14735. BABYLON.Tools.CheckExtends(minBox, min, max);
  14736. BABYLON.Tools.CheckExtends(maxBox, min, max);
  14737. }
  14738. }
  14739. return {
  14740. min: min,
  14741. max: max
  14742. };
  14743. };
  14744. /**
  14745. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  14746. * Returns the AbstractMesh.
  14747. */
  14748. AbstractMesh.prototype._updateBoundingInfo = function () {
  14749. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  14750. this._boundingInfo.update(this.worldMatrixFromCache);
  14751. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14752. return this;
  14753. };
  14754. /**
  14755. * Update a mesh's children BoundingInfo objects only.
  14756. * Returns the AbstractMesh.
  14757. */
  14758. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  14759. if (!this.subMeshes) {
  14760. return this;
  14761. }
  14762. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  14763. var subMesh = this.subMeshes[subIndex];
  14764. if (!subMesh.IsGlobal) {
  14765. subMesh.updateBoundingInfo(matrix);
  14766. }
  14767. }
  14768. return this;
  14769. };
  14770. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  14771. // Bounding info
  14772. this._updateBoundingInfo();
  14773. };
  14774. /**
  14775. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  14776. * A mesh is in the frustum if its bounding box intersects the frustum.
  14777. * Boolean returned.
  14778. */
  14779. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  14780. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  14781. };
  14782. /**
  14783. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  14784. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  14785. * Boolean returned.
  14786. */
  14787. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14788. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  14789. ;
  14790. };
  14791. /**
  14792. * True if the mesh intersects another mesh or a SolidParticle object.
  14793. * 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)
  14794. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  14795. * Returns a boolean.
  14796. */
  14797. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  14798. if (precise === void 0) { precise = false; }
  14799. if (!this._boundingInfo || !mesh._boundingInfo) {
  14800. return false;
  14801. }
  14802. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  14803. return true;
  14804. }
  14805. if (includeDescendants) {
  14806. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  14807. var child = _a[_i];
  14808. if (child.intersectsMesh(mesh, precise, true)) {
  14809. return true;
  14810. }
  14811. }
  14812. }
  14813. return false;
  14814. };
  14815. /**
  14816. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  14817. * Returns a boolean.
  14818. */
  14819. AbstractMesh.prototype.intersectsPoint = function (point) {
  14820. if (!this._boundingInfo) {
  14821. return false;
  14822. }
  14823. return this._boundingInfo.intersectsPoint(point);
  14824. };
  14825. AbstractMesh.prototype.getPhysicsImpostor = function () {
  14826. return this.physicsImpostor;
  14827. };
  14828. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  14829. if (camera === void 0) { camera = null; }
  14830. if (!camera) {
  14831. camera = this.getScene().activeCamera;
  14832. }
  14833. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  14834. };
  14835. /**
  14836. * Returns the distance from the mesh to the active camera.
  14837. * Returns a float.
  14838. */
  14839. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  14840. if (camera === void 0) { camera = null; }
  14841. if (!camera) {
  14842. camera = this.getScene().activeCamera;
  14843. }
  14844. return this.absolutePosition.subtract(camera.position).length();
  14845. };
  14846. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  14847. if (!this.physicsImpostor) {
  14848. return this;
  14849. }
  14850. this.physicsImpostor.applyImpulse(force, contactPoint);
  14851. return this;
  14852. };
  14853. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  14854. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  14855. return this;
  14856. }
  14857. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  14858. mainPivot: pivot1,
  14859. connectedPivot: pivot2,
  14860. nativeParams: options
  14861. });
  14862. return this;
  14863. };
  14864. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  14865. // Collisions
  14866. /**
  14867. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  14868. * Default `false`.
  14869. */
  14870. get: function () {
  14871. return this._checkCollisions;
  14872. },
  14873. set: function (collisionEnabled) {
  14874. this._checkCollisions = collisionEnabled;
  14875. if (this.getScene().workerCollisions) {
  14876. this.getScene().collisionCoordinator.onMeshUpdated(this);
  14877. }
  14878. },
  14879. enumerable: true,
  14880. configurable: true
  14881. });
  14882. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  14883. var globalPosition = this.getAbsolutePosition();
  14884. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  14885. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  14886. if (!this._collider) {
  14887. this._collider = new BABYLON.Collider();
  14888. }
  14889. this._collider.radius = this.ellipsoid;
  14890. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  14891. return this;
  14892. };
  14893. // Submeshes octree
  14894. /**
  14895. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  14896. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  14897. * Returns an Octree of submeshes.
  14898. */
  14899. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  14900. if (maxCapacity === void 0) { maxCapacity = 64; }
  14901. if (maxDepth === void 0) { maxDepth = 2; }
  14902. if (!this._submeshesOctree) {
  14903. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  14904. }
  14905. this.computeWorldMatrix(true);
  14906. var boundingInfo = this.getBoundingInfo();
  14907. // Update octree
  14908. var bbox = boundingInfo.boundingBox;
  14909. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  14910. return this._submeshesOctree;
  14911. };
  14912. // Collisions
  14913. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  14914. this._generatePointsArray();
  14915. if (!this._positions) {
  14916. return this;
  14917. }
  14918. // Transformation
  14919. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  14920. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  14921. subMesh._lastColliderWorldVertices = [];
  14922. subMesh._trianglePlanes = [];
  14923. var start = subMesh.verticesStart;
  14924. var end = (subMesh.verticesStart + subMesh.verticesCount);
  14925. for (var i = start; i < end; i++) {
  14926. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  14927. }
  14928. }
  14929. // Collide
  14930. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  14931. if (collider.collisionFound) {
  14932. collider.collidedMesh = this;
  14933. }
  14934. return this;
  14935. };
  14936. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  14937. var subMeshes;
  14938. var len;
  14939. // Octrees
  14940. if (this._submeshesOctree && this.useOctreeForCollisions) {
  14941. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  14942. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  14943. len = intersections.length;
  14944. subMeshes = intersections.data;
  14945. }
  14946. else {
  14947. subMeshes = this.subMeshes;
  14948. len = subMeshes.length;
  14949. }
  14950. for (var index = 0; index < len; index++) {
  14951. var subMesh = subMeshes[index];
  14952. // Bounding test
  14953. if (len > 1 && !subMesh._checkCollision(collider))
  14954. continue;
  14955. this._collideForSubMesh(subMesh, transformMatrix, collider);
  14956. }
  14957. return this;
  14958. };
  14959. AbstractMesh.prototype._checkCollision = function (collider) {
  14960. // Bounding box test
  14961. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  14962. return this;
  14963. // Transformation matrix
  14964. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  14965. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  14966. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  14967. return this;
  14968. };
  14969. // Picking
  14970. AbstractMesh.prototype._generatePointsArray = function () {
  14971. return false;
  14972. };
  14973. /**
  14974. * Checks if the passed Ray intersects with the mesh.
  14975. * Returns an object PickingInfo.
  14976. */
  14977. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  14978. var pickingInfo = new BABYLON.PickingInfo();
  14979. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  14980. return pickingInfo;
  14981. }
  14982. if (!this._generatePointsArray()) {
  14983. return pickingInfo;
  14984. }
  14985. var intersectInfo = null;
  14986. // Octrees
  14987. var subMeshes;
  14988. var len;
  14989. if (this._submeshesOctree && this.useOctreeForPicking) {
  14990. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  14991. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  14992. len = intersections.length;
  14993. subMeshes = intersections.data;
  14994. }
  14995. else {
  14996. subMeshes = this.subMeshes;
  14997. len = subMeshes.length;
  14998. }
  14999. for (var index = 0; index < len; index++) {
  15000. var subMesh = subMeshes[index];
  15001. // Bounding test
  15002. if (len > 1 && !subMesh.canIntersects(ray))
  15003. continue;
  15004. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  15005. if (currentIntersectInfo) {
  15006. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  15007. intersectInfo = currentIntersectInfo;
  15008. intersectInfo.subMeshId = index;
  15009. if (fastCheck) {
  15010. break;
  15011. }
  15012. }
  15013. }
  15014. }
  15015. if (intersectInfo) {
  15016. // Get picked point
  15017. var world = this.getWorldMatrix();
  15018. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  15019. var direction = ray.direction.clone();
  15020. direction = direction.scale(intersectInfo.distance);
  15021. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  15022. var pickedPoint = worldOrigin.add(worldDirection);
  15023. // Return result
  15024. pickingInfo.hit = true;
  15025. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  15026. pickingInfo.pickedPoint = pickedPoint;
  15027. pickingInfo.pickedMesh = this;
  15028. pickingInfo.bu = intersectInfo.bu || 0;
  15029. pickingInfo.bv = intersectInfo.bv || 0;
  15030. pickingInfo.faceId = intersectInfo.faceId;
  15031. pickingInfo.subMeshId = intersectInfo.subMeshId;
  15032. return pickingInfo;
  15033. }
  15034. return pickingInfo;
  15035. };
  15036. /**
  15037. * Clones the mesh, used by the class Mesh.
  15038. * Just returns `null` for an AbstractMesh.
  15039. */
  15040. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15041. return null;
  15042. };
  15043. /**
  15044. * Disposes all the mesh submeshes.
  15045. * Returns the AbstractMesh.
  15046. */
  15047. AbstractMesh.prototype.releaseSubMeshes = function () {
  15048. if (this.subMeshes) {
  15049. while (this.subMeshes.length) {
  15050. this.subMeshes[0].dispose();
  15051. }
  15052. }
  15053. else {
  15054. this.subMeshes = new Array();
  15055. }
  15056. return this;
  15057. };
  15058. /**
  15059. * Disposes the AbstractMesh.
  15060. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15061. * Returns nothing.
  15062. */
  15063. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  15064. var _this = this;
  15065. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  15066. var index;
  15067. // Action manager
  15068. if (this.actionManager) {
  15069. this.actionManager.dispose();
  15070. this.actionManager = null;
  15071. }
  15072. // Skeleton
  15073. this.skeleton = null;
  15074. // Physics
  15075. if (this.physicsImpostor) {
  15076. this.physicsImpostor.dispose();
  15077. }
  15078. // Intersections in progress
  15079. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  15080. var other = this._intersectionsInProgress[index];
  15081. var pos = other._intersectionsInProgress.indexOf(this);
  15082. other._intersectionsInProgress.splice(pos, 1);
  15083. }
  15084. this._intersectionsInProgress = [];
  15085. // Lights
  15086. var lights = this.getScene().lights;
  15087. lights.forEach(function (light) {
  15088. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  15089. if (meshIndex !== -1) {
  15090. light.includedOnlyMeshes.splice(meshIndex, 1);
  15091. }
  15092. meshIndex = light.excludedMeshes.indexOf(_this);
  15093. if (meshIndex !== -1) {
  15094. light.excludedMeshes.splice(meshIndex, 1);
  15095. }
  15096. // Shadow generators
  15097. var generator = light.getShadowGenerator();
  15098. if (generator) {
  15099. var shadowMap = generator.getShadowMap();
  15100. if (shadowMap && shadowMap.renderList) {
  15101. meshIndex = shadowMap.renderList.indexOf(_this);
  15102. if (meshIndex !== -1) {
  15103. shadowMap.renderList.splice(meshIndex, 1);
  15104. }
  15105. }
  15106. }
  15107. });
  15108. // Edges
  15109. if (this._edgesRenderer) {
  15110. this._edgesRenderer.dispose();
  15111. this._edgesRenderer = null;
  15112. }
  15113. // SubMeshes
  15114. if (this.getClassName() !== "InstancedMesh") {
  15115. this.releaseSubMeshes();
  15116. }
  15117. // Octree
  15118. var sceneOctree = this.getScene().selectionOctree;
  15119. if (sceneOctree) {
  15120. var index = sceneOctree.dynamicContent.indexOf(this);
  15121. if (index !== -1) {
  15122. sceneOctree.dynamicContent.splice(index, 1);
  15123. }
  15124. }
  15125. // Query
  15126. var engine = this.getScene().getEngine();
  15127. if (this._occlusionQuery) {
  15128. this._isOcclusionQueryInProgress = false;
  15129. engine.deleteQuery(this._occlusionQuery);
  15130. this._occlusionQuery = null;
  15131. }
  15132. // Engine
  15133. engine.wipeCaches();
  15134. // Remove from scene
  15135. this.getScene().removeMesh(this);
  15136. if (disposeMaterialAndTextures) {
  15137. if (this.material) {
  15138. this.material.dispose(false, true);
  15139. }
  15140. }
  15141. if (!doNotRecurse) {
  15142. // Particles
  15143. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  15144. if (this.getScene().particleSystems[index].emitter === this) {
  15145. this.getScene().particleSystems[index].dispose();
  15146. index--;
  15147. }
  15148. }
  15149. }
  15150. // facet data
  15151. if (this._facetDataEnabled) {
  15152. this.disableFacetData();
  15153. }
  15154. this.onAfterWorldMatrixUpdateObservable.clear();
  15155. this.onCollideObservable.clear();
  15156. this.onCollisionPositionChangeObservable.clear();
  15157. this._isDisposed = true;
  15158. _super.prototype.dispose.call(this, doNotRecurse);
  15159. };
  15160. /**
  15161. * Adds the passed mesh as a child to the current mesh.
  15162. * Returns the AbstractMesh.
  15163. */
  15164. AbstractMesh.prototype.addChild = function (mesh) {
  15165. mesh.setParent(this);
  15166. return this;
  15167. };
  15168. /**
  15169. * Removes the passed mesh from the current mesh children list.
  15170. * Returns the AbstractMesh.
  15171. */
  15172. AbstractMesh.prototype.removeChild = function (mesh) {
  15173. mesh.setParent(null);
  15174. return this;
  15175. };
  15176. // Facet data
  15177. /**
  15178. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  15179. * Returns the AbstractMesh.
  15180. */
  15181. AbstractMesh.prototype._initFacetData = function () {
  15182. if (!this._facetNormals) {
  15183. this._facetNormals = new Array();
  15184. }
  15185. if (!this._facetPositions) {
  15186. this._facetPositions = new Array();
  15187. }
  15188. if (!this._facetPartitioning) {
  15189. this._facetPartitioning = new Array();
  15190. }
  15191. this._facetNb = (this.getIndices().length / 3) | 0;
  15192. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  15193. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  15194. for (var f = 0; f < this._facetNb; f++) {
  15195. this._facetNormals[f] = BABYLON.Vector3.Zero();
  15196. this._facetPositions[f] = BABYLON.Vector3.Zero();
  15197. }
  15198. this._facetDataEnabled = true;
  15199. return this;
  15200. };
  15201. /**
  15202. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  15203. * This method can be called within the render loop.
  15204. * 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.
  15205. * Returns the AbstractMesh.
  15206. */
  15207. AbstractMesh.prototype.updateFacetData = function () {
  15208. if (!this._facetDataEnabled) {
  15209. this._initFacetData();
  15210. }
  15211. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15212. var indices = this.getIndices();
  15213. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15214. var bInfo = this.getBoundingInfo();
  15215. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  15216. // init arrays, matrix and sort function on first call
  15217. this._facetDepthSortEnabled = true;
  15218. if (indices instanceof Uint16Array) {
  15219. this._depthSortedIndices = new Uint16Array(indices);
  15220. }
  15221. else if (indices instanceof Uint32Array) {
  15222. this._depthSortedIndices = new Uint32Array(indices);
  15223. }
  15224. else {
  15225. var needs32bits = false;
  15226. for (var i = 0; i < indices.length; i++) {
  15227. if (indices[i] > 65535) {
  15228. needs32bits = true;
  15229. break;
  15230. }
  15231. }
  15232. if (needs32bits) {
  15233. this._depthSortedIndices = new Uint32Array(indices);
  15234. }
  15235. else {
  15236. this._depthSortedIndices = new Uint16Array(indices);
  15237. }
  15238. }
  15239. this._facetDepthSortFunction = function (f1, f2) {
  15240. return (f2.sqDistance - f1.sqDistance);
  15241. };
  15242. if (!this._facetDepthSortFrom) {
  15243. var camera = this.getScene().activeCamera;
  15244. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  15245. }
  15246. this._depthSortedFacets = [];
  15247. for (var f = 0; f < this._facetNb; f++) {
  15248. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  15249. this._depthSortedFacets.push(depthSortedFacet);
  15250. }
  15251. this._invertedMatrix = BABYLON.Matrix.Identity();
  15252. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  15253. }
  15254. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  15255. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  15256. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  15257. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  15258. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  15259. this._subDiv.max = this._partitioningSubdivisions;
  15260. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  15261. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  15262. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  15263. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  15264. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  15265. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  15266. // set the parameters for ComputeNormals()
  15267. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  15268. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  15269. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  15270. this._facetParameters.bInfo = bInfo;
  15271. this._facetParameters.bbSize = this._bbSize;
  15272. this._facetParameters.subDiv = this._subDiv;
  15273. this._facetParameters.ratio = this.partitioningBBoxRatio;
  15274. this._facetParameters.depthSort = this._facetDepthSort;
  15275. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  15276. this.computeWorldMatrix(true);
  15277. this._worldMatrix.invertToRef(this._invertedMatrix);
  15278. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  15279. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  15280. }
  15281. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  15282. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  15283. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  15284. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  15285. var l = (this._depthSortedIndices.length / 3) | 0;
  15286. for (var f = 0; f < l; f++) {
  15287. var sind = this._depthSortedFacets[f].ind;
  15288. this._depthSortedIndices[f * 3] = indices[sind];
  15289. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  15290. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  15291. }
  15292. this.updateIndices(this._depthSortedIndices);
  15293. }
  15294. return this;
  15295. };
  15296. /**
  15297. * Returns the facetLocalNormals array.
  15298. * The normals are expressed in the mesh local space.
  15299. */
  15300. AbstractMesh.prototype.getFacetLocalNormals = function () {
  15301. if (!this._facetNormals) {
  15302. this.updateFacetData();
  15303. }
  15304. return this._facetNormals;
  15305. };
  15306. /**
  15307. * Returns the facetLocalPositions array.
  15308. * The facet positions are expressed in the mesh local space.
  15309. */
  15310. AbstractMesh.prototype.getFacetLocalPositions = function () {
  15311. if (!this._facetPositions) {
  15312. this.updateFacetData();
  15313. }
  15314. return this._facetPositions;
  15315. };
  15316. /**
  15317. * Returns the facetLocalPartioning array.
  15318. */
  15319. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  15320. if (!this._facetPartitioning) {
  15321. this.updateFacetData();
  15322. }
  15323. return this._facetPartitioning;
  15324. };
  15325. /**
  15326. * Returns the i-th facet position in the world system.
  15327. * This method allocates a new Vector3 per call.
  15328. */
  15329. AbstractMesh.prototype.getFacetPosition = function (i) {
  15330. var pos = BABYLON.Vector3.Zero();
  15331. this.getFacetPositionToRef(i, pos);
  15332. return pos;
  15333. };
  15334. /**
  15335. * Sets the reference Vector3 with the i-th facet position in the world system.
  15336. * Returns the AbstractMesh.
  15337. */
  15338. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  15339. var localPos = (this.getFacetLocalPositions())[i];
  15340. var world = this.getWorldMatrix();
  15341. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  15342. return this;
  15343. };
  15344. /**
  15345. * Returns the i-th facet normal in the world system.
  15346. * This method allocates a new Vector3 per call.
  15347. */
  15348. AbstractMesh.prototype.getFacetNormal = function (i) {
  15349. var norm = BABYLON.Vector3.Zero();
  15350. this.getFacetNormalToRef(i, norm);
  15351. return norm;
  15352. };
  15353. /**
  15354. * Sets the reference Vector3 with the i-th facet normal in the world system.
  15355. * Returns the AbstractMesh.
  15356. */
  15357. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  15358. var localNorm = (this.getFacetLocalNormals())[i];
  15359. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  15360. return this;
  15361. };
  15362. /**
  15363. * 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).
  15364. */
  15365. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  15366. var bInfo = this.getBoundingInfo();
  15367. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  15368. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  15369. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  15370. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  15371. return null;
  15372. }
  15373. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  15374. };
  15375. /**
  15376. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  15377. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  15378. * 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.
  15379. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  15380. * 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.
  15381. */
  15382. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  15383. if (checkFace === void 0) { checkFace = false; }
  15384. if (facing === void 0) { facing = true; }
  15385. var world = this.getWorldMatrix();
  15386. var invMat = BABYLON.Tmp.Matrix[5];
  15387. world.invertToRef(invMat);
  15388. var invVect = BABYLON.Tmp.Vector3[8];
  15389. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  15390. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  15391. if (projected) {
  15392. // tranform the local computed projected vector to world coordinates
  15393. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  15394. }
  15395. return closest;
  15396. };
  15397. /**
  15398. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  15399. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  15400. * 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.
  15401. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  15402. * 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.
  15403. */
  15404. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  15405. if (checkFace === void 0) { checkFace = false; }
  15406. if (facing === void 0) { facing = true; }
  15407. var closest = null;
  15408. var tmpx = 0.0;
  15409. var tmpy = 0.0;
  15410. var tmpz = 0.0;
  15411. var d = 0.0; // tmp dot facet normal * facet position
  15412. var t0 = 0.0;
  15413. var projx = 0.0;
  15414. var projy = 0.0;
  15415. var projz = 0.0;
  15416. // Get all the facets in the same partitioning block than (x, y, z)
  15417. var facetPositions = this.getFacetLocalPositions();
  15418. var facetNormals = this.getFacetLocalNormals();
  15419. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  15420. if (!facetsInBlock) {
  15421. return null;
  15422. }
  15423. // Get the closest facet to (x, y, z)
  15424. var shortest = Number.MAX_VALUE; // init distance vars
  15425. var tmpDistance = shortest;
  15426. var fib; // current facet in the block
  15427. var norm; // current facet normal
  15428. var p0; // current facet barycenter position
  15429. // loop on all the facets in the current partitioning block
  15430. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  15431. fib = facetsInBlock[idx];
  15432. norm = facetNormals[fib];
  15433. p0 = facetPositions[fib];
  15434. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  15435. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  15436. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  15437. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  15438. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  15439. projx = x + norm.x * t0;
  15440. projy = y + norm.y * t0;
  15441. projz = z + norm.z * t0;
  15442. tmpx = projx - x;
  15443. tmpy = projy - y;
  15444. tmpz = projz - z;
  15445. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  15446. if (tmpDistance < shortest) {
  15447. shortest = tmpDistance;
  15448. closest = fib;
  15449. if (projected) {
  15450. projected.x = projx;
  15451. projected.y = projy;
  15452. projected.z = projz;
  15453. }
  15454. }
  15455. }
  15456. }
  15457. return closest;
  15458. };
  15459. /**
  15460. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  15461. */
  15462. AbstractMesh.prototype.getFacetDataParameters = function () {
  15463. return this._facetParameters;
  15464. };
  15465. /**
  15466. * Disables the feature FacetData and frees the related memory.
  15467. * Returns the AbstractMesh.
  15468. */
  15469. AbstractMesh.prototype.disableFacetData = function () {
  15470. if (this._facetDataEnabled) {
  15471. this._facetDataEnabled = false;
  15472. this._facetPositions = new Array();
  15473. this._facetNormals = new Array();
  15474. this._facetPartitioning = new Array();
  15475. this._facetParameters = null;
  15476. this._depthSortedIndices = new Uint32Array(0);
  15477. }
  15478. return this;
  15479. };
  15480. /**
  15481. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  15482. * Returns the mesh.
  15483. */
  15484. AbstractMesh.prototype.updateIndices = function (indices) {
  15485. return this;
  15486. };
  15487. /**
  15488. * The mesh Geometry. Actually used by the Mesh object.
  15489. * Returns a blank geometry object.
  15490. */
  15491. /**
  15492. * Creates new normals data for the mesh.
  15493. * @param updatable.
  15494. */
  15495. AbstractMesh.prototype.createNormals = function (updatable) {
  15496. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15497. var indices = this.getIndices();
  15498. var normals;
  15499. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15500. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15501. }
  15502. else {
  15503. normals = [];
  15504. }
  15505. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  15506. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  15507. };
  15508. AbstractMesh.prototype.checkOcclusionQuery = function () {
  15509. var engine = this.getEngine();
  15510. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  15511. this._isOccluded = false;
  15512. return;
  15513. }
  15514. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  15515. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  15516. if (isOcclusionQueryAvailable) {
  15517. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  15518. this._isOcclusionQueryInProgress = false;
  15519. this._occlusionInternalRetryCounter = 0;
  15520. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  15521. }
  15522. else {
  15523. this._occlusionInternalRetryCounter++;
  15524. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  15525. this._isOcclusionQueryInProgress = false;
  15526. this._occlusionInternalRetryCounter = 0;
  15527. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  15528. // if strict continue the last state of the object.
  15529. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  15530. }
  15531. else {
  15532. return;
  15533. }
  15534. }
  15535. }
  15536. var scene = this.getScene();
  15537. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  15538. if (!this._occlusionQuery) {
  15539. this._occlusionQuery = engine.createQuery();
  15540. }
  15541. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  15542. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  15543. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  15544. this._isOcclusionQueryInProgress = true;
  15545. };
  15546. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  15547. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  15548. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  15549. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  15550. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  15551. return AbstractMesh;
  15552. }(BABYLON.TransformNode));
  15553. BABYLON.AbstractMesh = AbstractMesh;
  15554. })(BABYLON || (BABYLON = {}));
  15555. //# sourceMappingURL=babylon.abstractMesh.js.map
  15556. var BABYLON;
  15557. (function (BABYLON) {
  15558. var Light = /** @class */ (function (_super) {
  15559. __extends(Light, _super);
  15560. /**
  15561. * Creates a Light object in the scene.
  15562. * Documentation : http://doc.babylonjs.com/tutorials/lights
  15563. */
  15564. function Light(name, scene) {
  15565. var _this = _super.call(this, name, scene) || this;
  15566. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  15567. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  15568. _this.intensity = 1.0;
  15569. _this.range = Number.MAX_VALUE;
  15570. /**
  15571. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  15572. * of light.
  15573. */
  15574. _this._photometricScale = 1.0;
  15575. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  15576. _this._radius = 0.00001;
  15577. _this.renderPriority = 0;
  15578. /**
  15579. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  15580. * the current shadow generator.
  15581. */
  15582. _this.shadowEnabled = true;
  15583. _this._excludeWithLayerMask = 0;
  15584. _this._includeOnlyWithLayerMask = 0;
  15585. _this._lightmapMode = 0;
  15586. _this._excludedMeshesIds = new Array();
  15587. _this._includedOnlyMeshesIds = new Array();
  15588. _this.getScene().addLight(_this);
  15589. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  15590. _this._buildUniformLayout();
  15591. _this.includedOnlyMeshes = new Array();
  15592. _this.excludedMeshes = new Array();
  15593. _this._resyncMeshes();
  15594. return _this;
  15595. }
  15596. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  15597. /**
  15598. * If every light affecting the material is in this lightmapMode,
  15599. * material.lightmapTexture adds or multiplies
  15600. * (depends on material.useLightmapAsShadowmap)
  15601. * after every other light calculations.
  15602. */
  15603. get: function () {
  15604. return Light._LIGHTMAP_DEFAULT;
  15605. },
  15606. enumerable: true,
  15607. configurable: true
  15608. });
  15609. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  15610. /**
  15611. * material.lightmapTexture as only diffuse lighting from this light
  15612. * adds pnly specular lighting from this light
  15613. * adds dynamic shadows
  15614. */
  15615. get: function () {
  15616. return Light._LIGHTMAP_SPECULAR;
  15617. },
  15618. enumerable: true,
  15619. configurable: true
  15620. });
  15621. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  15622. /**
  15623. * material.lightmapTexture as only lighting
  15624. * no light calculation from this light
  15625. * only adds dynamic shadows from this light
  15626. */
  15627. get: function () {
  15628. return Light._LIGHTMAP_SHADOWSONLY;
  15629. },
  15630. enumerable: true,
  15631. configurable: true
  15632. });
  15633. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  15634. /**
  15635. * Each light type uses the default quantity according to its type:
  15636. * point/spot lights use luminous intensity
  15637. * directional lights use illuminance
  15638. */
  15639. get: function () {
  15640. return Light._INTENSITYMODE_AUTOMATIC;
  15641. },
  15642. enumerable: true,
  15643. configurable: true
  15644. });
  15645. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  15646. /**
  15647. * lumen (lm)
  15648. */
  15649. get: function () {
  15650. return Light._INTENSITYMODE_LUMINOUSPOWER;
  15651. },
  15652. enumerable: true,
  15653. configurable: true
  15654. });
  15655. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  15656. /**
  15657. * candela (lm/sr)
  15658. */
  15659. get: function () {
  15660. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  15661. },
  15662. enumerable: true,
  15663. configurable: true
  15664. });
  15665. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  15666. /**
  15667. * lux (lm/m^2)
  15668. */
  15669. get: function () {
  15670. return Light._INTENSITYMODE_ILLUMINANCE;
  15671. },
  15672. enumerable: true,
  15673. configurable: true
  15674. });
  15675. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  15676. /**
  15677. * nit (cd/m^2)
  15678. */
  15679. get: function () {
  15680. return Light._INTENSITYMODE_LUMINANCE;
  15681. },
  15682. enumerable: true,
  15683. configurable: true
  15684. });
  15685. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  15686. /**
  15687. * Light type const id of the point light.
  15688. */
  15689. get: function () {
  15690. return Light._LIGHTTYPEID_POINTLIGHT;
  15691. },
  15692. enumerable: true,
  15693. configurable: true
  15694. });
  15695. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  15696. /**
  15697. * Light type const id of the directional light.
  15698. */
  15699. get: function () {
  15700. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  15701. },
  15702. enumerable: true,
  15703. configurable: true
  15704. });
  15705. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  15706. /**
  15707. * Light type const id of the spot light.
  15708. */
  15709. get: function () {
  15710. return Light._LIGHTTYPEID_SPOTLIGHT;
  15711. },
  15712. enumerable: true,
  15713. configurable: true
  15714. });
  15715. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  15716. /**
  15717. * Light type const id of the hemispheric light.
  15718. */
  15719. get: function () {
  15720. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  15721. },
  15722. enumerable: true,
  15723. configurable: true
  15724. });
  15725. Object.defineProperty(Light.prototype, "intensityMode", {
  15726. /**
  15727. * Gets the photometric scale used to interpret the intensity.
  15728. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15729. */
  15730. get: function () {
  15731. return this._intensityMode;
  15732. },
  15733. /**
  15734. * Sets the photometric scale used to interpret the intensity.
  15735. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15736. */
  15737. set: function (value) {
  15738. this._intensityMode = value;
  15739. this._computePhotometricScale();
  15740. },
  15741. enumerable: true,
  15742. configurable: true
  15743. });
  15744. ;
  15745. ;
  15746. Object.defineProperty(Light.prototype, "radius", {
  15747. /**
  15748. * Gets the light radius used by PBR Materials to simulate soft area lights.
  15749. */
  15750. get: function () {
  15751. return this._radius;
  15752. },
  15753. /**
  15754. * sets the light radius used by PBR Materials to simulate soft area lights.
  15755. */
  15756. set: function (value) {
  15757. this._radius = value;
  15758. this._computePhotometricScale();
  15759. },
  15760. enumerable: true,
  15761. configurable: true
  15762. });
  15763. ;
  15764. ;
  15765. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  15766. get: function () {
  15767. return this._includedOnlyMeshes;
  15768. },
  15769. set: function (value) {
  15770. this._includedOnlyMeshes = value;
  15771. this._hookArrayForIncludedOnly(value);
  15772. },
  15773. enumerable: true,
  15774. configurable: true
  15775. });
  15776. Object.defineProperty(Light.prototype, "excludedMeshes", {
  15777. get: function () {
  15778. return this._excludedMeshes;
  15779. },
  15780. set: function (value) {
  15781. this._excludedMeshes = value;
  15782. this._hookArrayForExcluded(value);
  15783. },
  15784. enumerable: true,
  15785. configurable: true
  15786. });
  15787. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  15788. get: function () {
  15789. return this._excludeWithLayerMask;
  15790. },
  15791. set: function (value) {
  15792. this._excludeWithLayerMask = value;
  15793. this._resyncMeshes();
  15794. },
  15795. enumerable: true,
  15796. configurable: true
  15797. });
  15798. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  15799. get: function () {
  15800. return this._includeOnlyWithLayerMask;
  15801. },
  15802. set: function (value) {
  15803. this._includeOnlyWithLayerMask = value;
  15804. this._resyncMeshes();
  15805. },
  15806. enumerable: true,
  15807. configurable: true
  15808. });
  15809. Object.defineProperty(Light.prototype, "lightmapMode", {
  15810. get: function () {
  15811. return this._lightmapMode;
  15812. },
  15813. set: function (value) {
  15814. if (this._lightmapMode === value) {
  15815. return;
  15816. }
  15817. this._lightmapMode = value;
  15818. this._markMeshesAsLightDirty();
  15819. },
  15820. enumerable: true,
  15821. configurable: true
  15822. });
  15823. Light.prototype._buildUniformLayout = function () {
  15824. // Overridden
  15825. };
  15826. /**
  15827. * Returns the string "Light".
  15828. */
  15829. Light.prototype.getClassName = function () {
  15830. return "Light";
  15831. };
  15832. /**
  15833. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15834. */
  15835. Light.prototype.toString = function (fullDetails) {
  15836. var ret = "Name: " + this.name;
  15837. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  15838. if (this.animations) {
  15839. for (var i = 0; i < this.animations.length; i++) {
  15840. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15841. }
  15842. }
  15843. if (fullDetails) {
  15844. }
  15845. return ret;
  15846. };
  15847. /**
  15848. * Set the enabled state of this node.
  15849. * @param {boolean} value - the new enabled state
  15850. * @see isEnabled
  15851. */
  15852. Light.prototype.setEnabled = function (value) {
  15853. _super.prototype.setEnabled.call(this, value);
  15854. this._resyncMeshes();
  15855. };
  15856. /**
  15857. * Returns the Light associated shadow generator.
  15858. */
  15859. Light.prototype.getShadowGenerator = function () {
  15860. return this._shadowGenerator;
  15861. };
  15862. /**
  15863. * Returns a Vector3, the absolute light position in the World.
  15864. */
  15865. Light.prototype.getAbsolutePosition = function () {
  15866. return BABYLON.Vector3.Zero();
  15867. };
  15868. Light.prototype.transferToEffect = function (effect, lightIndex) {
  15869. };
  15870. Light.prototype._getWorldMatrix = function () {
  15871. return BABYLON.Matrix.Identity();
  15872. };
  15873. /**
  15874. * Boolean : True if the light will affect the passed mesh.
  15875. */
  15876. Light.prototype.canAffectMesh = function (mesh) {
  15877. if (!mesh) {
  15878. return true;
  15879. }
  15880. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  15881. return false;
  15882. }
  15883. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  15884. return false;
  15885. }
  15886. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  15887. return false;
  15888. }
  15889. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  15890. return false;
  15891. }
  15892. return true;
  15893. };
  15894. /**
  15895. * Returns the light World matrix.
  15896. */
  15897. Light.prototype.getWorldMatrix = function () {
  15898. this._currentRenderId = this.getScene().getRenderId();
  15899. var worldMatrix = this._getWorldMatrix();
  15900. if (this.parent && this.parent.getWorldMatrix) {
  15901. if (!this._parentedWorldMatrix) {
  15902. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  15903. }
  15904. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  15905. this._markSyncedWithParent();
  15906. return this._parentedWorldMatrix;
  15907. }
  15908. return worldMatrix;
  15909. };
  15910. /**
  15911. * Sort function to order lights for rendering.
  15912. * @param a First Light object to compare to second.
  15913. * @param b Second Light object to compare first.
  15914. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  15915. */
  15916. Light.compareLightsPriority = function (a, b) {
  15917. //shadow-casting lights have priority over non-shadow-casting lights
  15918. //the renderPrioirty is a secondary sort criterion
  15919. if (a.shadowEnabled !== b.shadowEnabled) {
  15920. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  15921. }
  15922. return b.renderPriority - a.renderPriority;
  15923. };
  15924. /**
  15925. * Disposes the light.
  15926. */
  15927. Light.prototype.dispose = function () {
  15928. if (this._shadowGenerator) {
  15929. this._shadowGenerator.dispose();
  15930. this._shadowGenerator = null;
  15931. }
  15932. // Animations
  15933. this.getScene().stopAnimation(this);
  15934. // Remove from meshes
  15935. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15936. var mesh = _a[_i];
  15937. mesh._removeLightSource(this);
  15938. }
  15939. this._uniformBuffer.dispose();
  15940. // Remove from scene
  15941. this.getScene().removeLight(this);
  15942. _super.prototype.dispose.call(this);
  15943. };
  15944. /**
  15945. * Returns the light type ID (integer).
  15946. */
  15947. Light.prototype.getTypeID = function () {
  15948. return 0;
  15949. };
  15950. /**
  15951. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  15952. */
  15953. Light.prototype.getScaledIntensity = function () {
  15954. return this._photometricScale * this.intensity;
  15955. };
  15956. /**
  15957. * Returns a new Light object, named "name", from the current one.
  15958. */
  15959. Light.prototype.clone = function (name) {
  15960. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  15961. if (!constructor) {
  15962. return null;
  15963. }
  15964. return BABYLON.SerializationHelper.Clone(constructor, this);
  15965. };
  15966. /**
  15967. * Serializes the current light into a Serialization object.
  15968. * Returns the serialized object.
  15969. */
  15970. Light.prototype.serialize = function () {
  15971. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15972. // Type
  15973. serializationObject.type = this.getTypeID();
  15974. // Parent
  15975. if (this.parent) {
  15976. serializationObject.parentId = this.parent.id;
  15977. }
  15978. // Inclusion / exclusions
  15979. if (this.excludedMeshes.length > 0) {
  15980. serializationObject.excludedMeshesIds = [];
  15981. this.excludedMeshes.forEach(function (mesh) {
  15982. serializationObject.excludedMeshesIds.push(mesh.id);
  15983. });
  15984. }
  15985. if (this.includedOnlyMeshes.length > 0) {
  15986. serializationObject.includedOnlyMeshesIds = [];
  15987. this.includedOnlyMeshes.forEach(function (mesh) {
  15988. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  15989. });
  15990. }
  15991. // Animations
  15992. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15993. serializationObject.ranges = this.serializeAnimationRanges();
  15994. return serializationObject;
  15995. };
  15996. /**
  15997. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  15998. * This new light is named "name" and added to the passed scene.
  15999. */
  16000. Light.GetConstructorFromName = function (type, name, scene) {
  16001. switch (type) {
  16002. case 0:
  16003. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  16004. case 1:
  16005. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  16006. case 2:
  16007. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  16008. case 3:
  16009. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  16010. }
  16011. return null;
  16012. };
  16013. /**
  16014. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  16015. */
  16016. Light.Parse = function (parsedLight, scene) {
  16017. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  16018. if (!constructor) {
  16019. return null;
  16020. }
  16021. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  16022. // Inclusion / exclusions
  16023. if (parsedLight.excludedMeshesIds) {
  16024. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  16025. }
  16026. if (parsedLight.includedOnlyMeshesIds) {
  16027. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  16028. }
  16029. // Parent
  16030. if (parsedLight.parentId) {
  16031. light._waitingParentId = parsedLight.parentId;
  16032. }
  16033. // Animations
  16034. if (parsedLight.animations) {
  16035. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  16036. var parsedAnimation = parsedLight.animations[animationIndex];
  16037. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16038. }
  16039. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  16040. }
  16041. if (parsedLight.autoAnimate) {
  16042. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  16043. }
  16044. return light;
  16045. };
  16046. Light.prototype._hookArrayForExcluded = function (array) {
  16047. var _this = this;
  16048. var oldPush = array.push;
  16049. array.push = function () {
  16050. var items = [];
  16051. for (var _i = 0; _i < arguments.length; _i++) {
  16052. items[_i] = arguments[_i];
  16053. }
  16054. var result = oldPush.apply(array, items);
  16055. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  16056. var item = items_1[_a];
  16057. item._resyncLighSource(_this);
  16058. }
  16059. return result;
  16060. };
  16061. var oldSplice = array.splice;
  16062. array.splice = function (index, deleteCount) {
  16063. var deleted = oldSplice.apply(array, [index, deleteCount]);
  16064. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  16065. var item = deleted_1[_i];
  16066. item._resyncLighSource(_this);
  16067. }
  16068. return deleted;
  16069. };
  16070. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  16071. var item = array_1[_i];
  16072. item._resyncLighSource(this);
  16073. }
  16074. };
  16075. Light.prototype._hookArrayForIncludedOnly = function (array) {
  16076. var _this = this;
  16077. var oldPush = array.push;
  16078. array.push = function () {
  16079. var items = [];
  16080. for (var _i = 0; _i < arguments.length; _i++) {
  16081. items[_i] = arguments[_i];
  16082. }
  16083. var result = oldPush.apply(array, items);
  16084. _this._resyncMeshes();
  16085. return result;
  16086. };
  16087. var oldSplice = array.splice;
  16088. array.splice = function (index, deleteCount) {
  16089. var deleted = oldSplice.apply(array, [index, deleteCount]);
  16090. _this._resyncMeshes();
  16091. return deleted;
  16092. };
  16093. this._resyncMeshes();
  16094. };
  16095. Light.prototype._resyncMeshes = function () {
  16096. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  16097. var mesh = _a[_i];
  16098. mesh._resyncLighSource(this);
  16099. }
  16100. };
  16101. Light.prototype._markMeshesAsLightDirty = function () {
  16102. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  16103. var mesh = _a[_i];
  16104. if (mesh._lightSources.indexOf(this) !== -1) {
  16105. mesh._markSubMeshesAsLightDirty();
  16106. }
  16107. }
  16108. };
  16109. /**
  16110. * Recomputes the cached photometric scale if needed.
  16111. */
  16112. Light.prototype._computePhotometricScale = function () {
  16113. this._photometricScale = this._getPhotometricScale();
  16114. this.getScene().resetCachedMaterial();
  16115. };
  16116. /**
  16117. * Returns the Photometric Scale according to the light type and intensity mode.
  16118. */
  16119. Light.prototype._getPhotometricScale = function () {
  16120. var photometricScale = 0.0;
  16121. var lightTypeID = this.getTypeID();
  16122. //get photometric mode
  16123. var photometricMode = this.intensityMode;
  16124. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  16125. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  16126. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  16127. }
  16128. else {
  16129. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  16130. }
  16131. }
  16132. //compute photometric scale
  16133. switch (lightTypeID) {
  16134. case Light.LIGHTTYPEID_POINTLIGHT:
  16135. case Light.LIGHTTYPEID_SPOTLIGHT:
  16136. switch (photometricMode) {
  16137. case Light.INTENSITYMODE_LUMINOUSPOWER:
  16138. photometricScale = 1.0 / (4.0 * Math.PI);
  16139. break;
  16140. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  16141. photometricScale = 1.0;
  16142. break;
  16143. case Light.INTENSITYMODE_LUMINANCE:
  16144. photometricScale = this.radius * this.radius;
  16145. break;
  16146. }
  16147. break;
  16148. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  16149. switch (photometricMode) {
  16150. case Light.INTENSITYMODE_ILLUMINANCE:
  16151. photometricScale = 1.0;
  16152. break;
  16153. case Light.INTENSITYMODE_LUMINANCE:
  16154. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  16155. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  16156. var apexAngleRadians = this.radius;
  16157. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  16158. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  16159. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  16160. photometricScale = solidAngle;
  16161. break;
  16162. }
  16163. break;
  16164. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  16165. // No fall off in hemisperic light.
  16166. photometricScale = 1.0;
  16167. break;
  16168. }
  16169. return photometricScale;
  16170. };
  16171. Light.prototype._reorderLightsInScene = function () {
  16172. var scene = this.getScene();
  16173. if (this._renderPriority != 0) {
  16174. scene.requireLightSorting = true;
  16175. }
  16176. this.getScene().sortLightsByPriority();
  16177. };
  16178. //lightmapMode Consts
  16179. Light._LIGHTMAP_DEFAULT = 0;
  16180. Light._LIGHTMAP_SPECULAR = 1;
  16181. Light._LIGHTMAP_SHADOWSONLY = 2;
  16182. // Intensity Mode Consts
  16183. Light._INTENSITYMODE_AUTOMATIC = 0;
  16184. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  16185. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  16186. Light._INTENSITYMODE_ILLUMINANCE = 3;
  16187. Light._INTENSITYMODE_LUMINANCE = 4;
  16188. // Light types ids const.
  16189. Light._LIGHTTYPEID_POINTLIGHT = 0;
  16190. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  16191. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  16192. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  16193. __decorate([
  16194. BABYLON.serializeAsColor3()
  16195. ], Light.prototype, "diffuse", void 0);
  16196. __decorate([
  16197. BABYLON.serializeAsColor3()
  16198. ], Light.prototype, "specular", void 0);
  16199. __decorate([
  16200. BABYLON.serialize()
  16201. ], Light.prototype, "intensity", void 0);
  16202. __decorate([
  16203. BABYLON.serialize()
  16204. ], Light.prototype, "range", void 0);
  16205. __decorate([
  16206. BABYLON.serialize()
  16207. ], Light.prototype, "intensityMode", null);
  16208. __decorate([
  16209. BABYLON.serialize()
  16210. ], Light.prototype, "radius", null);
  16211. __decorate([
  16212. BABYLON.serialize()
  16213. ], Light.prototype, "_renderPriority", void 0);
  16214. __decorate([
  16215. BABYLON.expandToProperty("_reorderLightsInScene")
  16216. ], Light.prototype, "renderPriority", void 0);
  16217. __decorate([
  16218. BABYLON.serialize()
  16219. ], Light.prototype, "shadowEnabled", void 0);
  16220. __decorate([
  16221. BABYLON.serialize("excludeWithLayerMask")
  16222. ], Light.prototype, "_excludeWithLayerMask", void 0);
  16223. __decorate([
  16224. BABYLON.serialize("includeOnlyWithLayerMask")
  16225. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  16226. __decorate([
  16227. BABYLON.serialize("lightmapMode")
  16228. ], Light.prototype, "_lightmapMode", void 0);
  16229. return Light;
  16230. }(BABYLON.Node));
  16231. BABYLON.Light = Light;
  16232. })(BABYLON || (BABYLON = {}));
  16233. //# sourceMappingURL=babylon.light.js.map
  16234. var BABYLON;
  16235. (function (BABYLON) {
  16236. var Camera = /** @class */ (function (_super) {
  16237. __extends(Camera, _super);
  16238. function Camera(name, position, scene) {
  16239. var _this = _super.call(this, name, scene) || this;
  16240. _this.upVector = BABYLON.Vector3.Up();
  16241. _this.orthoLeft = null;
  16242. _this.orthoRight = null;
  16243. _this.orthoBottom = null;
  16244. _this.orthoTop = null;
  16245. _this.fov = 0.8;
  16246. _this.minZ = 1;
  16247. _this.maxZ = 10000.0;
  16248. _this.inertia = 0.9;
  16249. _this.mode = Camera.PERSPECTIVE_CAMERA;
  16250. _this.isIntermediate = false;
  16251. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  16252. _this.layerMask = 0x0FFFFFFF;
  16253. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  16254. // Camera rig members
  16255. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  16256. _this._rigCameras = new Array();
  16257. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  16258. _this._skipRendering = false;
  16259. _this.customRenderTargets = new Array();
  16260. // Observables
  16261. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  16262. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  16263. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  16264. _this.onRestoreStateObservable = new BABYLON.Observable();
  16265. // Cache
  16266. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  16267. _this._projectionMatrix = new BABYLON.Matrix();
  16268. _this._doNotComputeProjectionMatrix = false;
  16269. _this._postProcesses = new Array();
  16270. _this._transformMatrix = BABYLON.Matrix.Zero();
  16271. _this._activeMeshes = new BABYLON.SmartArray(256);
  16272. _this._globalPosition = BABYLON.Vector3.Zero();
  16273. _this._refreshFrustumPlanes = true;
  16274. _this.getScene().addCamera(_this);
  16275. if (!_this.getScene().activeCamera) {
  16276. _this.getScene().activeCamera = _this;
  16277. }
  16278. _this.position = position;
  16279. return _this;
  16280. }
  16281. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  16282. get: function () {
  16283. return Camera._PERSPECTIVE_CAMERA;
  16284. },
  16285. enumerable: true,
  16286. configurable: true
  16287. });
  16288. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  16289. get: function () {
  16290. return Camera._ORTHOGRAPHIC_CAMERA;
  16291. },
  16292. enumerable: true,
  16293. configurable: true
  16294. });
  16295. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  16296. get: function () {
  16297. return Camera._FOVMODE_VERTICAL_FIXED;
  16298. },
  16299. enumerable: true,
  16300. configurable: true
  16301. });
  16302. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  16303. get: function () {
  16304. return Camera._FOVMODE_HORIZONTAL_FIXED;
  16305. },
  16306. enumerable: true,
  16307. configurable: true
  16308. });
  16309. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  16310. get: function () {
  16311. return Camera._RIG_MODE_NONE;
  16312. },
  16313. enumerable: true,
  16314. configurable: true
  16315. });
  16316. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  16317. get: function () {
  16318. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  16319. },
  16320. enumerable: true,
  16321. configurable: true
  16322. });
  16323. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  16324. get: function () {
  16325. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  16326. },
  16327. enumerable: true,
  16328. configurable: true
  16329. });
  16330. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  16331. get: function () {
  16332. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16333. },
  16334. enumerable: true,
  16335. configurable: true
  16336. });
  16337. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  16338. get: function () {
  16339. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  16340. },
  16341. enumerable: true,
  16342. configurable: true
  16343. });
  16344. Object.defineProperty(Camera, "RIG_MODE_VR", {
  16345. get: function () {
  16346. return Camera._RIG_MODE_VR;
  16347. },
  16348. enumerable: true,
  16349. configurable: true
  16350. });
  16351. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  16352. get: function () {
  16353. return Camera._RIG_MODE_WEBVR;
  16354. },
  16355. enumerable: true,
  16356. configurable: true
  16357. });
  16358. /**
  16359. * Store current camera state (fov, position, etc..)
  16360. */
  16361. Camera.prototype.storeState = function () {
  16362. this._stateStored = true;
  16363. this._storedFov = this.fov;
  16364. return this;
  16365. };
  16366. /**
  16367. * Restores the camera state values if it has been stored. You must call storeState() first
  16368. */
  16369. Camera.prototype._restoreStateValues = function () {
  16370. if (!this._stateStored) {
  16371. return false;
  16372. }
  16373. this.fov = this._storedFov;
  16374. return true;
  16375. };
  16376. /**
  16377. * Restored camera state. You must call storeState() first
  16378. */
  16379. Camera.prototype.restoreState = function () {
  16380. if (this._restoreStateValues()) {
  16381. this.onRestoreStateObservable.notifyObservers(this);
  16382. return true;
  16383. }
  16384. return false;
  16385. };
  16386. Camera.prototype.getClassName = function () {
  16387. return "Camera";
  16388. };
  16389. /**
  16390. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16391. */
  16392. Camera.prototype.toString = function (fullDetails) {
  16393. var ret = "Name: " + this.name;
  16394. ret += ", type: " + this.getClassName();
  16395. if (this.animations) {
  16396. for (var i = 0; i < this.animations.length; i++) {
  16397. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16398. }
  16399. }
  16400. if (fullDetails) {
  16401. }
  16402. return ret;
  16403. };
  16404. Object.defineProperty(Camera.prototype, "globalPosition", {
  16405. get: function () {
  16406. return this._globalPosition;
  16407. },
  16408. enumerable: true,
  16409. configurable: true
  16410. });
  16411. Camera.prototype.getActiveMeshes = function () {
  16412. return this._activeMeshes;
  16413. };
  16414. Camera.prototype.isActiveMesh = function (mesh) {
  16415. return (this._activeMeshes.indexOf(mesh) !== -1);
  16416. };
  16417. //Cache
  16418. Camera.prototype._initCache = function () {
  16419. _super.prototype._initCache.call(this);
  16420. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16421. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16422. this._cache.mode = undefined;
  16423. this._cache.minZ = undefined;
  16424. this._cache.maxZ = undefined;
  16425. this._cache.fov = undefined;
  16426. this._cache.fovMode = undefined;
  16427. this._cache.aspectRatio = undefined;
  16428. this._cache.orthoLeft = undefined;
  16429. this._cache.orthoRight = undefined;
  16430. this._cache.orthoBottom = undefined;
  16431. this._cache.orthoTop = undefined;
  16432. this._cache.renderWidth = undefined;
  16433. this._cache.renderHeight = undefined;
  16434. };
  16435. Camera.prototype._updateCache = function (ignoreParentClass) {
  16436. if (!ignoreParentClass) {
  16437. _super.prototype._updateCache.call(this);
  16438. }
  16439. this._cache.position.copyFrom(this.position);
  16440. this._cache.upVector.copyFrom(this.upVector);
  16441. };
  16442. // Synchronized
  16443. Camera.prototype._isSynchronized = function () {
  16444. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  16445. };
  16446. Camera.prototype._isSynchronizedViewMatrix = function () {
  16447. if (!_super.prototype._isSynchronized.call(this))
  16448. return false;
  16449. return this._cache.position.equals(this.position)
  16450. && this._cache.upVector.equals(this.upVector)
  16451. && this.isSynchronizedWithParent();
  16452. };
  16453. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  16454. var check = this._cache.mode === this.mode
  16455. && this._cache.minZ === this.minZ
  16456. && this._cache.maxZ === this.maxZ;
  16457. if (!check) {
  16458. return false;
  16459. }
  16460. var engine = this.getEngine();
  16461. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16462. check = this._cache.fov === this.fov
  16463. && this._cache.fovMode === this.fovMode
  16464. && this._cache.aspectRatio === engine.getAspectRatio(this);
  16465. }
  16466. else {
  16467. check = this._cache.orthoLeft === this.orthoLeft
  16468. && this._cache.orthoRight === this.orthoRight
  16469. && this._cache.orthoBottom === this.orthoBottom
  16470. && this._cache.orthoTop === this.orthoTop
  16471. && this._cache.renderWidth === engine.getRenderWidth()
  16472. && this._cache.renderHeight === engine.getRenderHeight();
  16473. }
  16474. return check;
  16475. };
  16476. // Controls
  16477. Camera.prototype.attachControl = function (element, noPreventDefault) {
  16478. };
  16479. Camera.prototype.detachControl = function (element) {
  16480. };
  16481. Camera.prototype.update = function () {
  16482. this._checkInputs();
  16483. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16484. this._updateRigCameras();
  16485. }
  16486. };
  16487. Camera.prototype._checkInputs = function () {
  16488. this.onAfterCheckInputsObservable.notifyObservers(this);
  16489. };
  16490. Object.defineProperty(Camera.prototype, "rigCameras", {
  16491. get: function () {
  16492. return this._rigCameras;
  16493. },
  16494. enumerable: true,
  16495. configurable: true
  16496. });
  16497. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  16498. get: function () {
  16499. return this._rigPostProcess;
  16500. },
  16501. enumerable: true,
  16502. configurable: true
  16503. });
  16504. Camera.prototype._cascadePostProcessesToRigCams = function () {
  16505. // invalidate framebuffer
  16506. if (this._postProcesses.length > 0) {
  16507. this._postProcesses[0].markTextureDirty();
  16508. }
  16509. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  16510. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  16511. var cam = this._rigCameras[i];
  16512. var rigPostProcess = cam._rigPostProcess;
  16513. // for VR rig, there does not have to be a post process
  16514. if (rigPostProcess) {
  16515. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  16516. if (isPass) {
  16517. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  16518. cam.isIntermediate = this._postProcesses.length === 0;
  16519. }
  16520. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  16521. rigPostProcess.markTextureDirty();
  16522. }
  16523. else {
  16524. cam._postProcesses = this._postProcesses.slice(0);
  16525. }
  16526. }
  16527. };
  16528. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  16529. if (insertAt === void 0) { insertAt = null; }
  16530. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  16531. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  16532. return 0;
  16533. }
  16534. if (insertAt == null || insertAt < 0) {
  16535. this._postProcesses.push(postProcess);
  16536. }
  16537. else {
  16538. this._postProcesses.splice(insertAt, 0, postProcess);
  16539. }
  16540. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16541. return this._postProcesses.indexOf(postProcess);
  16542. };
  16543. Camera.prototype.detachPostProcess = function (postProcess) {
  16544. var idx = this._postProcesses.indexOf(postProcess);
  16545. if (idx !== -1) {
  16546. this._postProcesses.splice(idx, 1);
  16547. }
  16548. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16549. };
  16550. Camera.prototype.getWorldMatrix = function () {
  16551. if (!this._worldMatrix) {
  16552. this._worldMatrix = BABYLON.Matrix.Identity();
  16553. }
  16554. var viewMatrix = this.getViewMatrix();
  16555. viewMatrix.invertToRef(this._worldMatrix);
  16556. return this._worldMatrix;
  16557. };
  16558. Camera.prototype._getViewMatrix = function () {
  16559. return BABYLON.Matrix.Identity();
  16560. };
  16561. Camera.prototype.getViewMatrix = function (force) {
  16562. if (!force && this._isSynchronizedViewMatrix()) {
  16563. return this._computedViewMatrix;
  16564. }
  16565. this.updateCache();
  16566. this._computedViewMatrix = this._getViewMatrix();
  16567. this._currentRenderId = this.getScene().getRenderId();
  16568. this._refreshFrustumPlanes = true;
  16569. if (!this.parent || !this.parent.getWorldMatrix) {
  16570. this._globalPosition.copyFrom(this.position);
  16571. }
  16572. else {
  16573. if (!this._worldMatrix) {
  16574. this._worldMatrix = BABYLON.Matrix.Identity();
  16575. }
  16576. this._computedViewMatrix.invertToRef(this._worldMatrix);
  16577. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  16578. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  16579. this._computedViewMatrix.invert();
  16580. this._markSyncedWithParent();
  16581. }
  16582. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  16583. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  16584. }
  16585. this.onViewMatrixChangedObservable.notifyObservers(this);
  16586. return this._computedViewMatrix;
  16587. };
  16588. Camera.prototype.freezeProjectionMatrix = function (projection) {
  16589. this._doNotComputeProjectionMatrix = true;
  16590. if (projection !== undefined) {
  16591. this._projectionMatrix = projection;
  16592. }
  16593. };
  16594. ;
  16595. Camera.prototype.unfreezeProjectionMatrix = function () {
  16596. this._doNotComputeProjectionMatrix = false;
  16597. };
  16598. ;
  16599. Camera.prototype.getProjectionMatrix = function (force) {
  16600. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  16601. return this._projectionMatrix;
  16602. }
  16603. // Cache
  16604. this._cache.mode = this.mode;
  16605. this._cache.minZ = this.minZ;
  16606. this._cache.maxZ = this.maxZ;
  16607. // Matrix
  16608. this._refreshFrustumPlanes = true;
  16609. var engine = this.getEngine();
  16610. var scene = this.getScene();
  16611. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16612. this._cache.fov = this.fov;
  16613. this._cache.fovMode = this.fovMode;
  16614. this._cache.aspectRatio = engine.getAspectRatio(this);
  16615. if (this.minZ <= 0) {
  16616. this.minZ = 0.1;
  16617. }
  16618. if (scene.useRightHandedSystem) {
  16619. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16620. }
  16621. else {
  16622. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16623. }
  16624. }
  16625. else {
  16626. var halfWidth = engine.getRenderWidth() / 2.0;
  16627. var halfHeight = engine.getRenderHeight() / 2.0;
  16628. if (scene.useRightHandedSystem) {
  16629. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16630. }
  16631. else {
  16632. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16633. }
  16634. this._cache.orthoLeft = this.orthoLeft;
  16635. this._cache.orthoRight = this.orthoRight;
  16636. this._cache.orthoBottom = this.orthoBottom;
  16637. this._cache.orthoTop = this.orthoTop;
  16638. this._cache.renderWidth = engine.getRenderWidth();
  16639. this._cache.renderHeight = engine.getRenderHeight();
  16640. }
  16641. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  16642. return this._projectionMatrix;
  16643. };
  16644. Camera.prototype.getTranformationMatrix = function () {
  16645. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16646. return this._transformMatrix;
  16647. };
  16648. Camera.prototype.updateFrustumPlanes = function () {
  16649. if (!this._refreshFrustumPlanes) {
  16650. return;
  16651. }
  16652. this.getTranformationMatrix();
  16653. if (!this._frustumPlanes) {
  16654. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16655. }
  16656. else {
  16657. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16658. }
  16659. this._refreshFrustumPlanes = false;
  16660. };
  16661. Camera.prototype.isInFrustum = function (target) {
  16662. this.updateFrustumPlanes();
  16663. return target.isInFrustum(this._frustumPlanes);
  16664. };
  16665. Camera.prototype.isCompletelyInFrustum = function (target) {
  16666. this.updateFrustumPlanes();
  16667. return target.isCompletelyInFrustum(this._frustumPlanes);
  16668. };
  16669. Camera.prototype.getForwardRay = function (length, transform, origin) {
  16670. if (length === void 0) { length = 100; }
  16671. if (!transform) {
  16672. transform = this.getWorldMatrix();
  16673. }
  16674. if (!origin) {
  16675. origin = this.position;
  16676. }
  16677. var forward = new BABYLON.Vector3(0, 0, 1);
  16678. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  16679. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  16680. return new BABYLON.Ray(origin, direction, length);
  16681. };
  16682. Camera.prototype.dispose = function () {
  16683. // Observables
  16684. this.onViewMatrixChangedObservable.clear();
  16685. this.onProjectionMatrixChangedObservable.clear();
  16686. this.onAfterCheckInputsObservable.clear();
  16687. this.onRestoreStateObservable.clear();
  16688. // Inputs
  16689. if (this.inputs) {
  16690. this.inputs.clear();
  16691. }
  16692. // Animations
  16693. this.getScene().stopAnimation(this);
  16694. // Remove from scene
  16695. this.getScene().removeCamera(this);
  16696. while (this._rigCameras.length > 0) {
  16697. var camera = this._rigCameras.pop();
  16698. if (camera) {
  16699. camera.dispose();
  16700. }
  16701. }
  16702. // Postprocesses
  16703. if (this._rigPostProcess) {
  16704. this._rigPostProcess.dispose(this);
  16705. this._rigPostProcess = null;
  16706. this._postProcesses = [];
  16707. }
  16708. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16709. this._rigPostProcess = null;
  16710. this._postProcesses = [];
  16711. }
  16712. else {
  16713. var i = this._postProcesses.length;
  16714. while (--i >= 0) {
  16715. this._postProcesses[i].dispose(this);
  16716. }
  16717. }
  16718. // Render targets
  16719. var i = this.customRenderTargets.length;
  16720. while (--i >= 0) {
  16721. this.customRenderTargets[i].dispose();
  16722. }
  16723. this.customRenderTargets = [];
  16724. // Active Meshes
  16725. this._activeMeshes.dispose();
  16726. _super.prototype.dispose.call(this);
  16727. };
  16728. Object.defineProperty(Camera.prototype, "leftCamera", {
  16729. // ---- Camera rigs section ----
  16730. get: function () {
  16731. if (this._rigCameras.length < 1) {
  16732. return null;
  16733. }
  16734. return this._rigCameras[0];
  16735. },
  16736. enumerable: true,
  16737. configurable: true
  16738. });
  16739. Object.defineProperty(Camera.prototype, "rightCamera", {
  16740. get: function () {
  16741. if (this._rigCameras.length < 2) {
  16742. return null;
  16743. }
  16744. return this._rigCameras[1];
  16745. },
  16746. enumerable: true,
  16747. configurable: true
  16748. });
  16749. Camera.prototype.getLeftTarget = function () {
  16750. if (this._rigCameras.length < 1) {
  16751. return null;
  16752. }
  16753. return this._rigCameras[0].getTarget();
  16754. };
  16755. Camera.prototype.getRightTarget = function () {
  16756. if (this._rigCameras.length < 2) {
  16757. return null;
  16758. }
  16759. return this._rigCameras[1].getTarget();
  16760. };
  16761. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  16762. if (this.cameraRigMode === mode) {
  16763. return;
  16764. }
  16765. while (this._rigCameras.length > 0) {
  16766. var camera = this._rigCameras.pop();
  16767. if (camera) {
  16768. camera.dispose();
  16769. }
  16770. }
  16771. this.cameraRigMode = mode;
  16772. this._cameraRigParams = {};
  16773. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  16774. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  16775. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  16776. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  16777. // create the rig cameras, unless none
  16778. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16779. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  16780. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  16781. if (leftCamera && rightCamera) {
  16782. this._rigCameras.push(leftCamera);
  16783. this._rigCameras.push(rightCamera);
  16784. }
  16785. }
  16786. switch (this.cameraRigMode) {
  16787. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16788. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16789. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  16790. break;
  16791. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16792. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16793. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16794. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16795. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16796. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  16797. break;
  16798. case Camera.RIG_MODE_VR:
  16799. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  16800. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  16801. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16802. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16803. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  16804. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  16805. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  16806. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  16807. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16808. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16809. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  16810. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  16811. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  16812. if (metrics.compensateDistortion) {
  16813. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  16814. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  16815. }
  16816. break;
  16817. case Camera.RIG_MODE_WEBVR:
  16818. if (rigParams.vrDisplay) {
  16819. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  16820. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  16821. //Left eye
  16822. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16823. this._rigCameras[0].setCameraRigParameter("left", true);
  16824. //leaving this for future reference
  16825. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  16826. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  16827. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  16828. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16829. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16830. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16831. this._rigCameras[0].parent = this;
  16832. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  16833. //Right eye
  16834. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16835. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  16836. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  16837. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  16838. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16839. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16840. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16841. this._rigCameras[1].parent = this;
  16842. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  16843. if (Camera.UseAlternateWebVRRendering) {
  16844. this._rigCameras[1]._skipRendering = true;
  16845. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  16846. }
  16847. }
  16848. break;
  16849. }
  16850. this._cascadePostProcessesToRigCams();
  16851. this.update();
  16852. };
  16853. Camera.prototype._getVRProjectionMatrix = function () {
  16854. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  16855. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  16856. return this._projectionMatrix;
  16857. };
  16858. Camera.prototype._updateCameraRotationMatrix = function () {
  16859. //Here for WebVR
  16860. };
  16861. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  16862. //Here for WebVR
  16863. };
  16864. /**
  16865. * This function MUST be overwritten by the different WebVR cameras available.
  16866. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16867. */
  16868. Camera.prototype._getWebVRProjectionMatrix = function () {
  16869. return BABYLON.Matrix.Identity();
  16870. };
  16871. /**
  16872. * This function MUST be overwritten by the different WebVR cameras available.
  16873. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16874. */
  16875. Camera.prototype._getWebVRViewMatrix = function () {
  16876. return BABYLON.Matrix.Identity();
  16877. };
  16878. Camera.prototype.setCameraRigParameter = function (name, value) {
  16879. if (!this._cameraRigParams) {
  16880. this._cameraRigParams = {};
  16881. }
  16882. this._cameraRigParams[name] = value;
  16883. //provisionnally:
  16884. if (name === "interaxialDistance") {
  16885. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  16886. }
  16887. };
  16888. /**
  16889. * needs to be overridden by children so sub has required properties to be copied
  16890. */
  16891. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  16892. return null;
  16893. };
  16894. /**
  16895. * May need to be overridden by children
  16896. */
  16897. Camera.prototype._updateRigCameras = function () {
  16898. for (var i = 0; i < this._rigCameras.length; i++) {
  16899. this._rigCameras[i].minZ = this.minZ;
  16900. this._rigCameras[i].maxZ = this.maxZ;
  16901. this._rigCameras[i].fov = this.fov;
  16902. }
  16903. // only update viewport when ANAGLYPH
  16904. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  16905. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  16906. }
  16907. };
  16908. Camera.prototype._setupInputs = function () {
  16909. };
  16910. Camera.prototype.serialize = function () {
  16911. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16912. // Type
  16913. serializationObject.type = this.getClassName();
  16914. // Parent
  16915. if (this.parent) {
  16916. serializationObject.parentId = this.parent.id;
  16917. }
  16918. if (this.inputs) {
  16919. this.inputs.serialize(serializationObject);
  16920. }
  16921. // Animations
  16922. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16923. serializationObject.ranges = this.serializeAnimationRanges();
  16924. return serializationObject;
  16925. };
  16926. Camera.prototype.clone = function (name) {
  16927. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  16928. };
  16929. Camera.prototype.getDirection = function (localAxis) {
  16930. var result = BABYLON.Vector3.Zero();
  16931. this.getDirectionToRef(localAxis, result);
  16932. return result;
  16933. };
  16934. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  16935. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16936. };
  16937. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  16938. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  16939. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  16940. switch (type) {
  16941. case "ArcRotateCamera":
  16942. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  16943. case "DeviceOrientationCamera":
  16944. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  16945. case "FollowCamera":
  16946. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  16947. case "ArcFollowCamera":
  16948. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  16949. case "GamepadCamera":
  16950. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16951. case "TouchCamera":
  16952. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  16953. case "VirtualJoysticksCamera":
  16954. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  16955. case "WebVRFreeCamera":
  16956. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16957. case "WebVRGamepadCamera":
  16958. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16959. case "VRDeviceOrientationFreeCamera":
  16960. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16961. case "VRDeviceOrientationGamepadCamera":
  16962. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16963. case "AnaglyphArcRotateCamera":
  16964. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16965. case "AnaglyphFreeCamera":
  16966. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16967. case "AnaglyphGamepadCamera":
  16968. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16969. case "AnaglyphUniversalCamera":
  16970. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16971. case "StereoscopicArcRotateCamera":
  16972. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16973. case "StereoscopicFreeCamera":
  16974. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16975. case "StereoscopicGamepadCamera":
  16976. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16977. case "StereoscopicUniversalCamera":
  16978. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16979. case "FreeCamera":// Forcing Universal here
  16980. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16981. default:// Universal Camera is the default value
  16982. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16983. }
  16984. };
  16985. Camera.Parse = function (parsedCamera, scene) {
  16986. var type = parsedCamera.type;
  16987. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  16988. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  16989. // Parent
  16990. if (parsedCamera.parentId) {
  16991. camera._waitingParentId = parsedCamera.parentId;
  16992. }
  16993. //If camera has an input manager, let it parse inputs settings
  16994. if (camera.inputs) {
  16995. camera.inputs.parse(parsedCamera);
  16996. camera._setupInputs();
  16997. }
  16998. if (camera.setPosition) {
  16999. camera.position.copyFromFloats(0, 0, 0);
  17000. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  17001. }
  17002. // Target
  17003. if (parsedCamera.target) {
  17004. if (camera.setTarget) {
  17005. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  17006. }
  17007. }
  17008. // Apply 3d rig, when found
  17009. if (parsedCamera.cameraRigMode) {
  17010. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  17011. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  17012. }
  17013. // Animations
  17014. if (parsedCamera.animations) {
  17015. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  17016. var parsedAnimation = parsedCamera.animations[animationIndex];
  17017. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17018. }
  17019. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  17020. }
  17021. if (parsedCamera.autoAnimate) {
  17022. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  17023. }
  17024. return camera;
  17025. };
  17026. // Statics
  17027. Camera._PERSPECTIVE_CAMERA = 0;
  17028. Camera._ORTHOGRAPHIC_CAMERA = 1;
  17029. Camera._FOVMODE_VERTICAL_FIXED = 0;
  17030. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  17031. Camera._RIG_MODE_NONE = 0;
  17032. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  17033. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  17034. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  17035. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  17036. Camera._RIG_MODE_VR = 20;
  17037. Camera._RIG_MODE_WEBVR = 21;
  17038. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  17039. Camera.UseAlternateWebVRRendering = false;
  17040. __decorate([
  17041. BABYLON.serializeAsVector3()
  17042. ], Camera.prototype, "position", void 0);
  17043. __decorate([
  17044. BABYLON.serializeAsVector3()
  17045. ], Camera.prototype, "upVector", void 0);
  17046. __decorate([
  17047. BABYLON.serialize()
  17048. ], Camera.prototype, "orthoLeft", void 0);
  17049. __decorate([
  17050. BABYLON.serialize()
  17051. ], Camera.prototype, "orthoRight", void 0);
  17052. __decorate([
  17053. BABYLON.serialize()
  17054. ], Camera.prototype, "orthoBottom", void 0);
  17055. __decorate([
  17056. BABYLON.serialize()
  17057. ], Camera.prototype, "orthoTop", void 0);
  17058. __decorate([
  17059. BABYLON.serialize()
  17060. ], Camera.prototype, "fov", void 0);
  17061. __decorate([
  17062. BABYLON.serialize()
  17063. ], Camera.prototype, "minZ", void 0);
  17064. __decorate([
  17065. BABYLON.serialize()
  17066. ], Camera.prototype, "maxZ", void 0);
  17067. __decorate([
  17068. BABYLON.serialize()
  17069. ], Camera.prototype, "inertia", void 0);
  17070. __decorate([
  17071. BABYLON.serialize()
  17072. ], Camera.prototype, "mode", void 0);
  17073. __decorate([
  17074. BABYLON.serialize()
  17075. ], Camera.prototype, "layerMask", void 0);
  17076. __decorate([
  17077. BABYLON.serialize()
  17078. ], Camera.prototype, "fovMode", void 0);
  17079. __decorate([
  17080. BABYLON.serialize()
  17081. ], Camera.prototype, "cameraRigMode", void 0);
  17082. __decorate([
  17083. BABYLON.serialize()
  17084. ], Camera.prototype, "interaxialDistance", void 0);
  17085. __decorate([
  17086. BABYLON.serialize()
  17087. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  17088. return Camera;
  17089. }(BABYLON.Node));
  17090. BABYLON.Camera = Camera;
  17091. })(BABYLON || (BABYLON = {}));
  17092. //# sourceMappingURL=babylon.camera.js.map
  17093. var BABYLON;
  17094. (function (BABYLON) {
  17095. var RenderingManager = /** @class */ (function () {
  17096. function RenderingManager(scene) {
  17097. this._renderingGroups = new Array();
  17098. this._autoClearDepthStencil = {};
  17099. this._customOpaqueSortCompareFn = {};
  17100. this._customAlphaTestSortCompareFn = {};
  17101. this._customTransparentSortCompareFn = {};
  17102. this._renderinGroupInfo = null;
  17103. this._scene = scene;
  17104. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  17105. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  17106. }
  17107. }
  17108. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  17109. if (depth === void 0) { depth = true; }
  17110. if (stencil === void 0) { stencil = true; }
  17111. if (this._depthStencilBufferAlreadyCleaned) {
  17112. return;
  17113. }
  17114. this._scene.getEngine().clear(null, false, depth, stencil);
  17115. this._depthStencilBufferAlreadyCleaned = true;
  17116. };
  17117. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  17118. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  17119. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  17120. var info = null;
  17121. if (observable) {
  17122. if (!this._renderinGroupInfo) {
  17123. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  17124. }
  17125. info = this._renderinGroupInfo;
  17126. info.scene = this._scene;
  17127. info.camera = this._scene.activeCamera;
  17128. }
  17129. // Dispatch sprites
  17130. if (renderSprites) {
  17131. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  17132. var manager = this._scene.spriteManagers[index];
  17133. this.dispatchSprites(manager);
  17134. }
  17135. }
  17136. // Render
  17137. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17138. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  17139. var renderingGroup = this._renderingGroups[index];
  17140. if (!renderingGroup && !observable)
  17141. continue;
  17142. var renderingGroupMask = 0;
  17143. // Fire PRECLEAR stage
  17144. if (observable && info) {
  17145. renderingGroupMask = Math.pow(2, index);
  17146. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  17147. info.renderingGroupId = index;
  17148. observable.notifyObservers(info, renderingGroupMask);
  17149. }
  17150. // Clear depth/stencil if needed
  17151. if (RenderingManager.AUTOCLEAR) {
  17152. var autoClear = this._autoClearDepthStencil[index];
  17153. if (autoClear && autoClear.autoClear) {
  17154. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  17155. }
  17156. }
  17157. if (observable && info) {
  17158. // Fire PREOPAQUE stage
  17159. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  17160. observable.notifyObservers(info, renderingGroupMask);
  17161. // Fire PRETRANSPARENT stage
  17162. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  17163. observable.notifyObservers(info, renderingGroupMask);
  17164. }
  17165. if (renderingGroup)
  17166. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  17167. // Fire POSTTRANSPARENT stage
  17168. if (observable && info) {
  17169. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  17170. observable.notifyObservers(info, renderingGroupMask);
  17171. }
  17172. }
  17173. };
  17174. RenderingManager.prototype.reset = function () {
  17175. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17176. var renderingGroup = this._renderingGroups[index];
  17177. if (renderingGroup) {
  17178. renderingGroup.prepare();
  17179. }
  17180. }
  17181. };
  17182. RenderingManager.prototype.dispose = function () {
  17183. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17184. var renderingGroup = this._renderingGroups[index];
  17185. if (renderingGroup) {
  17186. renderingGroup.dispose();
  17187. }
  17188. }
  17189. this._renderingGroups.length = 0;
  17190. };
  17191. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  17192. if (!this._renderingGroups[renderingGroupId]) {
  17193. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  17194. }
  17195. };
  17196. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  17197. var renderingGroupId = spriteManager.renderingGroupId || 0;
  17198. this._prepareRenderingGroup(renderingGroupId);
  17199. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  17200. };
  17201. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  17202. var renderingGroupId = particleSystem.renderingGroupId || 0;
  17203. this._prepareRenderingGroup(renderingGroupId);
  17204. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  17205. };
  17206. RenderingManager.prototype.dispatch = function (subMesh) {
  17207. var mesh = subMesh.getMesh();
  17208. var renderingGroupId = mesh.renderingGroupId || 0;
  17209. this._prepareRenderingGroup(renderingGroupId);
  17210. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  17211. };
  17212. /**
  17213. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  17214. * This allowed control for front to back rendering or reversly depending of the special needs.
  17215. *
  17216. * @param renderingGroupId The rendering group id corresponding to its index
  17217. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  17218. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  17219. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  17220. */
  17221. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17222. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17223. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17224. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17225. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  17226. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  17227. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  17228. if (this._renderingGroups[renderingGroupId]) {
  17229. var group = this._renderingGroups[renderingGroupId];
  17230. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  17231. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  17232. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  17233. }
  17234. };
  17235. /**
  17236. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  17237. *
  17238. * @param renderingGroupId The rendering group id corresponding to its index
  17239. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  17240. * @param depth Automatically clears depth between groups if true and autoClear is true.
  17241. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  17242. */
  17243. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  17244. if (depth === void 0) { depth = true; }
  17245. if (stencil === void 0) { stencil = true; }
  17246. this._autoClearDepthStencil[renderingGroupId] = {
  17247. autoClear: autoClearDepthStencil,
  17248. depth: depth,
  17249. stencil: stencil
  17250. };
  17251. };
  17252. /**
  17253. * The max id used for rendering groups (not included)
  17254. */
  17255. RenderingManager.MAX_RENDERINGGROUPS = 4;
  17256. /**
  17257. * The min id used for rendering groups (included)
  17258. */
  17259. RenderingManager.MIN_RENDERINGGROUPS = 0;
  17260. /**
  17261. * Used to globally prevent autoclearing scenes.
  17262. */
  17263. RenderingManager.AUTOCLEAR = true;
  17264. return RenderingManager;
  17265. }());
  17266. BABYLON.RenderingManager = RenderingManager;
  17267. })(BABYLON || (BABYLON = {}));
  17268. //# sourceMappingURL=babylon.renderingManager.js.map
  17269. var BABYLON;
  17270. (function (BABYLON) {
  17271. var RenderingGroup = /** @class */ (function () {
  17272. /**
  17273. * Creates a new rendering group.
  17274. * @param index The rendering group index
  17275. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  17276. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  17277. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  17278. */
  17279. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17280. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17281. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17282. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17283. this.index = index;
  17284. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  17285. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  17286. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  17287. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  17288. this._particleSystems = new BABYLON.SmartArray(256);
  17289. this._spriteManagers = new BABYLON.SmartArray(256);
  17290. this._edgesRenderers = new BABYLON.SmartArray(16);
  17291. this._scene = scene;
  17292. this.opaqueSortCompareFn = opaqueSortCompareFn;
  17293. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  17294. this.transparentSortCompareFn = transparentSortCompareFn;
  17295. }
  17296. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  17297. /**
  17298. * Set the opaque sort comparison function.
  17299. * If null the sub meshes will be render in the order they were created
  17300. */
  17301. set: function (value) {
  17302. this._opaqueSortCompareFn = value;
  17303. if (value) {
  17304. this._renderOpaque = this.renderOpaqueSorted;
  17305. }
  17306. else {
  17307. this._renderOpaque = RenderingGroup.renderUnsorted;
  17308. }
  17309. },
  17310. enumerable: true,
  17311. configurable: true
  17312. });
  17313. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  17314. /**
  17315. * Set the alpha test sort comparison function.
  17316. * If null the sub meshes will be render in the order they were created
  17317. */
  17318. set: function (value) {
  17319. this._alphaTestSortCompareFn = value;
  17320. if (value) {
  17321. this._renderAlphaTest = this.renderAlphaTestSorted;
  17322. }
  17323. else {
  17324. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  17325. }
  17326. },
  17327. enumerable: true,
  17328. configurable: true
  17329. });
  17330. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  17331. /**
  17332. * Set the transparent sort comparison function.
  17333. * If null the sub meshes will be render in the order they were created
  17334. */
  17335. set: function (value) {
  17336. if (value) {
  17337. this._transparentSortCompareFn = value;
  17338. }
  17339. else {
  17340. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  17341. }
  17342. this._renderTransparent = this.renderTransparentSorted;
  17343. },
  17344. enumerable: true,
  17345. configurable: true
  17346. });
  17347. /**
  17348. * Render all the sub meshes contained in the group.
  17349. * @param customRenderFunction Used to override the default render behaviour of the group.
  17350. * @returns true if rendered some submeshes.
  17351. */
  17352. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  17353. if (customRenderFunction) {
  17354. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  17355. return;
  17356. }
  17357. var engine = this._scene.getEngine();
  17358. // Depth only
  17359. if (this._depthOnlySubMeshes.length !== 0) {
  17360. engine.setAlphaTesting(true);
  17361. engine.setColorWrite(false);
  17362. this._renderAlphaTest(this._depthOnlySubMeshes);
  17363. engine.setAlphaTesting(false);
  17364. engine.setColorWrite(true);
  17365. }
  17366. // Opaque
  17367. if (this._opaqueSubMeshes.length !== 0) {
  17368. this._renderOpaque(this._opaqueSubMeshes);
  17369. }
  17370. // Alpha test
  17371. if (this._alphaTestSubMeshes.length !== 0) {
  17372. engine.setAlphaTesting(true);
  17373. this._renderAlphaTest(this._alphaTestSubMeshes);
  17374. engine.setAlphaTesting(false);
  17375. }
  17376. var stencilState = engine.getStencilBuffer();
  17377. engine.setStencilBuffer(false);
  17378. // Sprites
  17379. if (renderSprites) {
  17380. this._renderSprites();
  17381. }
  17382. // Particles
  17383. if (renderParticles) {
  17384. this._renderParticles(activeMeshes);
  17385. }
  17386. if (this.onBeforeTransparentRendering) {
  17387. this.onBeforeTransparentRendering();
  17388. }
  17389. // Transparent
  17390. if (this._transparentSubMeshes.length !== 0) {
  17391. this._renderTransparent(this._transparentSubMeshes);
  17392. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17393. }
  17394. // Set back stencil to false in case it changes before the edge renderer.
  17395. engine.setStencilBuffer(false);
  17396. // Edges
  17397. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  17398. this._edgesRenderers.data[edgesRendererIndex].render();
  17399. }
  17400. // Restore Stencil state.
  17401. engine.setStencilBuffer(stencilState);
  17402. };
  17403. /**
  17404. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  17405. * @param subMeshes The submeshes to render
  17406. */
  17407. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  17408. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  17409. };
  17410. /**
  17411. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  17412. * @param subMeshes The submeshes to render
  17413. */
  17414. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  17415. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  17416. };
  17417. /**
  17418. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  17419. * @param subMeshes The submeshes to render
  17420. */
  17421. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  17422. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  17423. };
  17424. /**
  17425. * Renders the submeshes in a specified order.
  17426. * @param subMeshes The submeshes to sort before render
  17427. * @param sortCompareFn The comparison function use to sort
  17428. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  17429. * @param transparent Specifies to activate blending if true
  17430. */
  17431. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  17432. var subIndex = 0;
  17433. var subMesh;
  17434. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  17435. for (; subIndex < subMeshes.length; subIndex++) {
  17436. subMesh = subMeshes.data[subIndex];
  17437. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  17438. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  17439. }
  17440. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  17441. if (sortCompareFn) {
  17442. sortedArray.sort(sortCompareFn);
  17443. }
  17444. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  17445. subMesh = sortedArray[subIndex];
  17446. if (transparent) {
  17447. var material = subMesh.getMaterial();
  17448. if (material && material.needDepthPrePass) {
  17449. var engine = material.getScene().getEngine();
  17450. engine.setColorWrite(false);
  17451. engine.setAlphaTesting(true);
  17452. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17453. subMesh.render(false);
  17454. engine.setAlphaTesting(false);
  17455. engine.setColorWrite(true);
  17456. }
  17457. }
  17458. subMesh.render(transparent);
  17459. }
  17460. };
  17461. /**
  17462. * Renders the submeshes in the order they were dispatched (no sort applied).
  17463. * @param subMeshes The submeshes to render
  17464. */
  17465. RenderingGroup.renderUnsorted = function (subMeshes) {
  17466. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  17467. var submesh = subMeshes.data[subIndex];
  17468. submesh.render(false);
  17469. }
  17470. };
  17471. /**
  17472. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17473. * are rendered back to front if in the same alpha index.
  17474. *
  17475. * @param a The first submesh
  17476. * @param b The second submesh
  17477. * @returns The result of the comparison
  17478. */
  17479. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  17480. // Alpha index first
  17481. if (a._alphaIndex > b._alphaIndex) {
  17482. return 1;
  17483. }
  17484. if (a._alphaIndex < b._alphaIndex) {
  17485. return -1;
  17486. }
  17487. // Then distance to camera
  17488. return RenderingGroup.backToFrontSortCompare(a, b);
  17489. };
  17490. /**
  17491. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17492. * are rendered back to front.
  17493. *
  17494. * @param a The first submesh
  17495. * @param b The second submesh
  17496. * @returns The result of the comparison
  17497. */
  17498. RenderingGroup.backToFrontSortCompare = function (a, b) {
  17499. // Then distance to camera
  17500. if (a._distanceToCamera < b._distanceToCamera) {
  17501. return 1;
  17502. }
  17503. if (a._distanceToCamera > b._distanceToCamera) {
  17504. return -1;
  17505. }
  17506. return 0;
  17507. };
  17508. /**
  17509. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17510. * are rendered front to back (prevent overdraw).
  17511. *
  17512. * @param a The first submesh
  17513. * @param b The second submesh
  17514. * @returns The result of the comparison
  17515. */
  17516. RenderingGroup.frontToBackSortCompare = function (a, b) {
  17517. // Then distance to camera
  17518. if (a._distanceToCamera < b._distanceToCamera) {
  17519. return -1;
  17520. }
  17521. if (a._distanceToCamera > b._distanceToCamera) {
  17522. return 1;
  17523. }
  17524. return 0;
  17525. };
  17526. /**
  17527. * Resets the different lists of submeshes to prepare a new frame.
  17528. */
  17529. RenderingGroup.prototype.prepare = function () {
  17530. this._opaqueSubMeshes.reset();
  17531. this._transparentSubMeshes.reset();
  17532. this._alphaTestSubMeshes.reset();
  17533. this._depthOnlySubMeshes.reset();
  17534. this._particleSystems.reset();
  17535. this._spriteManagers.reset();
  17536. this._edgesRenderers.reset();
  17537. };
  17538. RenderingGroup.prototype.dispose = function () {
  17539. this._opaqueSubMeshes.dispose();
  17540. this._transparentSubMeshes.dispose();
  17541. this._alphaTestSubMeshes.dispose();
  17542. this._depthOnlySubMeshes.dispose();
  17543. this._particleSystems.dispose();
  17544. this._spriteManagers.dispose();
  17545. this._edgesRenderers.dispose();
  17546. };
  17547. /**
  17548. * Inserts the submesh in its correct queue depending on its material.
  17549. * @param subMesh The submesh to dispatch
  17550. */
  17551. RenderingGroup.prototype.dispatch = function (subMesh) {
  17552. var material = subMesh.getMaterial();
  17553. var mesh = subMesh.getMesh();
  17554. if (!material) {
  17555. return;
  17556. }
  17557. if (material.needAlphaBlendingForMesh(mesh)) {
  17558. this._transparentSubMeshes.push(subMesh);
  17559. }
  17560. else if (material.needAlphaTesting()) {
  17561. if (material.needDepthPrePass) {
  17562. this._depthOnlySubMeshes.push(subMesh);
  17563. }
  17564. this._alphaTestSubMeshes.push(subMesh);
  17565. }
  17566. else {
  17567. if (material.needDepthPrePass) {
  17568. this._depthOnlySubMeshes.push(subMesh);
  17569. }
  17570. this._opaqueSubMeshes.push(subMesh); // Opaque
  17571. }
  17572. if (mesh._edgesRenderer) {
  17573. this._edgesRenderers.push(mesh._edgesRenderer);
  17574. }
  17575. };
  17576. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  17577. this._spriteManagers.push(spriteManager);
  17578. };
  17579. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  17580. this._particleSystems.push(particleSystem);
  17581. };
  17582. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  17583. if (this._particleSystems.length === 0) {
  17584. return;
  17585. }
  17586. // Particles
  17587. var activeCamera = this._scene.activeCamera;
  17588. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  17589. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  17590. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  17591. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  17592. continue;
  17593. }
  17594. var emitter = particleSystem.emitter;
  17595. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  17596. this._scene._activeParticles.addCount(particleSystem.render(), false);
  17597. }
  17598. }
  17599. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  17600. };
  17601. RenderingGroup.prototype._renderSprites = function () {
  17602. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  17603. return;
  17604. }
  17605. // Sprites
  17606. var activeCamera = this._scene.activeCamera;
  17607. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  17608. for (var id = 0; id < this._spriteManagers.length; id++) {
  17609. var spriteManager = this._spriteManagers.data[id];
  17610. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  17611. spriteManager.render();
  17612. }
  17613. }
  17614. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  17615. };
  17616. return RenderingGroup;
  17617. }());
  17618. BABYLON.RenderingGroup = RenderingGroup;
  17619. })(BABYLON || (BABYLON = {}));
  17620. //# sourceMappingURL=babylon.renderingGroup.js.map
  17621. var BABYLON;
  17622. (function (BABYLON) {
  17623. var ClickInfo = /** @class */ (function () {
  17624. function ClickInfo() {
  17625. this._singleClick = false;
  17626. this._doubleClick = false;
  17627. this._hasSwiped = false;
  17628. this._ignore = false;
  17629. }
  17630. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  17631. get: function () {
  17632. return this._singleClick;
  17633. },
  17634. set: function (b) {
  17635. this._singleClick = b;
  17636. },
  17637. enumerable: true,
  17638. configurable: true
  17639. });
  17640. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  17641. get: function () {
  17642. return this._doubleClick;
  17643. },
  17644. set: function (b) {
  17645. this._doubleClick = b;
  17646. },
  17647. enumerable: true,
  17648. configurable: true
  17649. });
  17650. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  17651. get: function () {
  17652. return this._hasSwiped;
  17653. },
  17654. set: function (b) {
  17655. this._hasSwiped = b;
  17656. },
  17657. enumerable: true,
  17658. configurable: true
  17659. });
  17660. Object.defineProperty(ClickInfo.prototype, "ignore", {
  17661. get: function () {
  17662. return this._ignore;
  17663. },
  17664. set: function (b) {
  17665. this._ignore = b;
  17666. },
  17667. enumerable: true,
  17668. configurable: true
  17669. });
  17670. return ClickInfo;
  17671. }());
  17672. /**
  17673. * This class is used by the onRenderingGroupObservable
  17674. */
  17675. var RenderingGroupInfo = /** @class */ (function () {
  17676. function RenderingGroupInfo() {
  17677. }
  17678. /**
  17679. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  17680. * This stage will be fired no matter what
  17681. */
  17682. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  17683. /**
  17684. * Called before opaque object are rendered.
  17685. * This stage will be fired only if there's 3D Opaque content to render
  17686. */
  17687. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  17688. /**
  17689. * Called after the opaque objects are rendered and before the transparent ones
  17690. * This stage will be fired only if there's 3D transparent content to render
  17691. */
  17692. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  17693. /**
  17694. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  17695. * This stage will be fired no matter what
  17696. */
  17697. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  17698. return RenderingGroupInfo;
  17699. }());
  17700. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  17701. /**
  17702. * Represents a scene to be rendered by the engine.
  17703. * @see http://doc.babylonjs.com/page.php?p=21911
  17704. */
  17705. var Scene = /** @class */ (function () {
  17706. /**
  17707. * @constructor
  17708. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  17709. */
  17710. function Scene(engine) {
  17711. // Members
  17712. this.autoClear = true;
  17713. this.autoClearDepthAndStencil = true;
  17714. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  17715. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  17716. this.forceWireframe = false;
  17717. this._forcePointsCloud = false;
  17718. this.forceShowBoundingBoxes = false;
  17719. this.animationsEnabled = true;
  17720. this.constantlyUpdateMeshUnderPointer = false;
  17721. this.hoverCursor = "pointer";
  17722. this.defaultCursor = "";
  17723. /**
  17724. * This is used to call preventDefault() on pointer down
  17725. * in order to block unwanted artifacts like system double clicks
  17726. */
  17727. this.preventDefaultOnPointerDown = true;
  17728. // Metadata
  17729. this.metadata = null;
  17730. /**
  17731. * An event triggered when the scene is disposed.
  17732. * @type {BABYLON.Observable}
  17733. */
  17734. this.onDisposeObservable = new BABYLON.Observable();
  17735. /**
  17736. * An event triggered before rendering the scene (right after animations and physics)
  17737. * @type {BABYLON.Observable}
  17738. */
  17739. this.onBeforeRenderObservable = new BABYLON.Observable();
  17740. /**
  17741. * An event triggered after rendering the scene
  17742. * @type {BABYLON.Observable}
  17743. */
  17744. this.onAfterRenderObservable = new BABYLON.Observable();
  17745. /**
  17746. * An event triggered before animating the scene
  17747. * @type {BABYLON.Observable}
  17748. */
  17749. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  17750. /**
  17751. * An event triggered after animations processing
  17752. * @type {BABYLON.Observable}
  17753. */
  17754. this.onAfterAnimationsObservable = new BABYLON.Observable();
  17755. /**
  17756. * An event triggered before draw calls are ready to be sent
  17757. * @type {BABYLON.Observable}
  17758. */
  17759. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  17760. /**
  17761. * An event triggered after draw calls have been sent
  17762. * @type {BABYLON.Observable}
  17763. */
  17764. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  17765. /**
  17766. * An event triggered when physic simulation is about to be run
  17767. * @type {BABYLON.Observable}
  17768. */
  17769. this.onBeforePhysicsObservable = new BABYLON.Observable();
  17770. /**
  17771. * An event triggered when physic simulation has been done
  17772. * @type {BABYLON.Observable}
  17773. */
  17774. this.onAfterPhysicsObservable = new BABYLON.Observable();
  17775. /**
  17776. * An event triggered when the scene is ready
  17777. * @type {BABYLON.Observable}
  17778. */
  17779. this.onReadyObservable = new BABYLON.Observable();
  17780. /**
  17781. * An event triggered before rendering a camera
  17782. * @type {BABYLON.Observable}
  17783. */
  17784. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  17785. /**
  17786. * An event triggered after rendering a camera
  17787. * @type {BABYLON.Observable}
  17788. */
  17789. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  17790. /**
  17791. * An event triggered when active meshes evaluation is about to start
  17792. * @type {BABYLON.Observable}
  17793. */
  17794. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17795. /**
  17796. * An event triggered when active meshes evaluation is done
  17797. * @type {BABYLON.Observable}
  17798. */
  17799. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17800. /**
  17801. * An event triggered when particles rendering is about to start
  17802. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  17803. * @type {BABYLON.Observable}
  17804. */
  17805. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  17806. /**
  17807. * An event triggered when particles rendering is done
  17808. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  17809. * @type {BABYLON.Observable}
  17810. */
  17811. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  17812. /**
  17813. * An event triggered when sprites rendering is about to start
  17814. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  17815. * @type {BABYLON.Observable}
  17816. */
  17817. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  17818. /**
  17819. * An event triggered when sprites rendering is done
  17820. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  17821. * @type {BABYLON.Observable}
  17822. */
  17823. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  17824. /**
  17825. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  17826. * @type {BABYLON.Observable}
  17827. */
  17828. this.onDataLoadedObservable = new BABYLON.Observable();
  17829. /**
  17830. * An event triggered when a camera is created
  17831. * @type {BABYLON.Observable}
  17832. */
  17833. this.onNewCameraAddedObservable = new BABYLON.Observable();
  17834. /**
  17835. * An event triggered when a camera is removed
  17836. * @type {BABYLON.Observable}
  17837. */
  17838. this.onCameraRemovedObservable = new BABYLON.Observable();
  17839. /**
  17840. * An event triggered when a light is created
  17841. * @type {BABYLON.Observable}
  17842. */
  17843. this.onNewLightAddedObservable = new BABYLON.Observable();
  17844. /**
  17845. * An event triggered when a light is removed
  17846. * @type {BABYLON.Observable}
  17847. */
  17848. this.onLightRemovedObservable = new BABYLON.Observable();
  17849. /**
  17850. * An event triggered when a geometry is created
  17851. * @type {BABYLON.Observable}
  17852. */
  17853. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  17854. /**
  17855. * An event triggered when a geometry is removed
  17856. * @type {BABYLON.Observable}
  17857. */
  17858. this.onGeometryRemovedObservable = new BABYLON.Observable();
  17859. /**
  17860. * An event triggered when a transform node is created
  17861. * @type {BABYLON.Observable}
  17862. */
  17863. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  17864. /**
  17865. * An event triggered when a transform node is removed
  17866. * @type {BABYLON.Observable}
  17867. */
  17868. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  17869. /**
  17870. * An event triggered when a mesh is created
  17871. * @type {BABYLON.Observable}
  17872. */
  17873. this.onNewMeshAddedObservable = new BABYLON.Observable();
  17874. /**
  17875. * An event triggered when a mesh is removed
  17876. * @type {BABYLON.Observable}
  17877. */
  17878. this.onMeshRemovedObservable = new BABYLON.Observable();
  17879. /**
  17880. * An event triggered when render targets are about to be rendered
  17881. * Can happen multiple times per frame.
  17882. * @type {BABYLON.Observable}
  17883. */
  17884. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  17885. /**
  17886. * An event triggered when render targets were rendered.
  17887. * Can happen multiple times per frame.
  17888. * @type {BABYLON.Observable}
  17889. */
  17890. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  17891. /**
  17892. * An event triggered before calculating deterministic simulation step
  17893. * @type {BABYLON.Observable}
  17894. */
  17895. this.onBeforeStepObservable = new BABYLON.Observable();
  17896. /**
  17897. * An event triggered after calculating deterministic simulation step
  17898. * @type {BABYLON.Observable}
  17899. */
  17900. this.onAfterStepObservable = new BABYLON.Observable();
  17901. /**
  17902. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  17903. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  17904. * 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)
  17905. */
  17906. this.onRenderingGroupObservable = new BABYLON.Observable();
  17907. // Animations
  17908. this.animations = [];
  17909. /**
  17910. * 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).
  17911. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  17912. */
  17913. this.onPrePointerObservable = new BABYLON.Observable();
  17914. /**
  17915. * Observable event triggered each time an input event is received from the rendering canvas
  17916. */
  17917. this.onPointerObservable = new BABYLON.Observable();
  17918. this._meshPickProceed = false;
  17919. this._currentPickResult = null;
  17920. this._previousPickResult = null;
  17921. this._totalPointersPressed = 0;
  17922. this._doubleClickOccured = false;
  17923. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  17924. this.cameraToUseForPointers = null;
  17925. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  17926. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  17927. this._startingPointerTime = 0;
  17928. this._previousStartingPointerTime = 0;
  17929. // Deterministic lockstep
  17930. this._timeAccumulator = 0;
  17931. this._currentStepId = 0;
  17932. this._currentInternalStep = 0;
  17933. // Keyboard
  17934. /**
  17935. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  17936. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  17937. */
  17938. this.onPreKeyboardObservable = new BABYLON.Observable();
  17939. /**
  17940. * Observable event triggered each time an keyboard event is received from the hosting window
  17941. */
  17942. this.onKeyboardObservable = new BABYLON.Observable();
  17943. // Coordinate system
  17944. /**
  17945. * use right-handed coordinate system on this scene.
  17946. * @type {boolean}
  17947. */
  17948. this._useRightHandedSystem = false;
  17949. // Fog
  17950. this._fogEnabled = true;
  17951. this._fogMode = Scene.FOGMODE_NONE;
  17952. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  17953. this.fogDensity = 0.1;
  17954. this.fogStart = 0;
  17955. this.fogEnd = 1000.0;
  17956. // Lights
  17957. /**
  17958. * is shadow enabled on this scene.
  17959. * @type {boolean}
  17960. */
  17961. this._shadowsEnabled = true;
  17962. /**
  17963. * is light enabled on this scene.
  17964. * @type {boolean}
  17965. */
  17966. this._lightsEnabled = true;
  17967. /**
  17968. * All of the lights added to this scene.
  17969. * @see BABYLON.Light
  17970. * @type {BABYLON.Light[]}
  17971. */
  17972. this.lights = new Array();
  17973. // Cameras
  17974. /** All of the cameras added to this scene. */
  17975. this.cameras = new Array();
  17976. /** All of the active cameras added to this scene. */
  17977. this.activeCameras = new Array();
  17978. // Meshes
  17979. /**
  17980. * All of the tranform nodes added to this scene.
  17981. * @see BABYLON.TransformNode
  17982. * @type {BABYLON.TransformNode[]}
  17983. */
  17984. this.transformNodes = new Array();
  17985. /**
  17986. * All of the (abstract) meshes added to this scene.
  17987. * @see BABYLON.AbstractMesh
  17988. * @type {BABYLON.AbstractMesh[]}
  17989. */
  17990. this.meshes = new Array();
  17991. // Geometries
  17992. this._geometries = new Array();
  17993. this.materials = new Array();
  17994. this.multiMaterials = new Array();
  17995. // Textures
  17996. this._texturesEnabled = true;
  17997. this.textures = new Array();
  17998. // Particles
  17999. this.particlesEnabled = true;
  18000. this.particleSystems = new Array();
  18001. // Sprites
  18002. this.spritesEnabled = true;
  18003. this.spriteManagers = new Array();
  18004. // Layers
  18005. this.layers = new Array();
  18006. this.highlightLayers = new Array();
  18007. // Skeletons
  18008. this._skeletonsEnabled = true;
  18009. this.skeletons = new Array();
  18010. // Morph targets
  18011. this.morphTargetManagers = new Array();
  18012. // Lens flares
  18013. this.lensFlaresEnabled = true;
  18014. this.lensFlareSystems = new Array();
  18015. // Collisions
  18016. this.collisionsEnabled = true;
  18017. /** Defines the gravity applied to this scene */
  18018. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  18019. // Postprocesses
  18020. this.postProcesses = new Array();
  18021. this.postProcessesEnabled = true;
  18022. // Customs render targets
  18023. this.renderTargetsEnabled = true;
  18024. this.dumpNextRenderTargets = false;
  18025. this.customRenderTargets = new Array();
  18026. // Imported meshes
  18027. this.importedMeshesFiles = new Array();
  18028. // Probes
  18029. this.probesEnabled = true;
  18030. this.reflectionProbes = new Array();
  18031. this._actionManagers = new Array();
  18032. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  18033. // Procedural textures
  18034. this.proceduralTexturesEnabled = true;
  18035. this._proceduralTextures = new Array();
  18036. this.soundTracks = new Array();
  18037. this._audioEnabled = true;
  18038. this._headphone = false;
  18039. // Performance counters
  18040. this._totalVertices = new BABYLON.PerfCounter();
  18041. this._activeIndices = new BABYLON.PerfCounter();
  18042. this._activeParticles = new BABYLON.PerfCounter();
  18043. this._activeBones = new BABYLON.PerfCounter();
  18044. this._animationTime = 0;
  18045. this.animationTimeScale = 1;
  18046. this._renderId = 0;
  18047. this._executeWhenReadyTimeoutId = -1;
  18048. this._intermediateRendering = false;
  18049. this._viewUpdateFlag = -1;
  18050. this._projectionUpdateFlag = -1;
  18051. this._alternateViewUpdateFlag = -1;
  18052. this._alternateProjectionUpdateFlag = -1;
  18053. this._toBeDisposed = new BABYLON.SmartArray(256);
  18054. this._pendingData = new Array();
  18055. this._isDisposed = false;
  18056. this._activeMeshes = new BABYLON.SmartArray(256);
  18057. this._processedMaterials = new BABYLON.SmartArray(256);
  18058. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  18059. this._activeParticleSystems = new BABYLON.SmartArray(256);
  18060. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  18061. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  18062. this._activeAnimatables = new Array();
  18063. this._transformMatrix = BABYLON.Matrix.Zero();
  18064. this._useAlternateCameraConfiguration = false;
  18065. this._alternateRendering = false;
  18066. this.requireLightSorting = false;
  18067. this._activeMeshesFrozen = false;
  18068. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  18069. this._engine.scenes.push(this);
  18070. this._uid = null;
  18071. this._renderingManager = new BABYLON.RenderingManager(this);
  18072. this.postProcessManager = new BABYLON.PostProcessManager(this);
  18073. if (BABYLON.OutlineRenderer) {
  18074. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  18075. }
  18076. if (BABYLON.Tools.IsWindowObjectExist()) {
  18077. this.attachControl();
  18078. }
  18079. //simplification queue
  18080. if (BABYLON.SimplificationQueue) {
  18081. this.simplificationQueue = new BABYLON.SimplificationQueue();
  18082. }
  18083. //collision coordinator initialization. For now legacy per default.
  18084. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  18085. // Uniform Buffer
  18086. this._createUbo();
  18087. // Default Image processing definition.
  18088. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  18089. }
  18090. Object.defineProperty(Scene, "FOGMODE_NONE", {
  18091. /** The fog is deactivated */
  18092. get: function () {
  18093. return Scene._FOGMODE_NONE;
  18094. },
  18095. enumerable: true,
  18096. configurable: true
  18097. });
  18098. Object.defineProperty(Scene, "FOGMODE_EXP", {
  18099. /** The fog density is following an exponential function */
  18100. get: function () {
  18101. return Scene._FOGMODE_EXP;
  18102. },
  18103. enumerable: true,
  18104. configurable: true
  18105. });
  18106. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  18107. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  18108. get: function () {
  18109. return Scene._FOGMODE_EXP2;
  18110. },
  18111. enumerable: true,
  18112. configurable: true
  18113. });
  18114. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  18115. /** The fog density is following a linear function. */
  18116. get: function () {
  18117. return Scene._FOGMODE_LINEAR;
  18118. },
  18119. enumerable: true,
  18120. configurable: true
  18121. });
  18122. Object.defineProperty(Scene.prototype, "environmentTexture", {
  18123. /**
  18124. * Texture used in all pbr material as the reflection texture.
  18125. * As in the majority of the scene they are the same (exception for multi room and so on),
  18126. * this is easier to reference from here than from all the materials.
  18127. */
  18128. get: function () {
  18129. return this._environmentTexture;
  18130. },
  18131. /**
  18132. * Texture used in all pbr material as the reflection texture.
  18133. * As in the majority of the scene they are the same (exception for multi room and so on),
  18134. * this is easier to set here than in all the materials.
  18135. */
  18136. set: function (value) {
  18137. if (this._environmentTexture === value) {
  18138. return;
  18139. }
  18140. this._environmentTexture = value;
  18141. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18142. },
  18143. enumerable: true,
  18144. configurable: true
  18145. });
  18146. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  18147. /**
  18148. * Default image processing configuration used either in the rendering
  18149. * Forward main pass or through the imageProcessingPostProcess if present.
  18150. * As in the majority of the scene they are the same (exception for multi camera),
  18151. * this is easier to reference from here than from all the materials and post process.
  18152. *
  18153. * No setter as we it is a shared configuration, you can set the values instead.
  18154. */
  18155. get: function () {
  18156. return this._imageProcessingConfiguration;
  18157. },
  18158. enumerable: true,
  18159. configurable: true
  18160. });
  18161. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  18162. get: function () {
  18163. return this._forcePointsCloud;
  18164. },
  18165. set: function (value) {
  18166. if (this._forcePointsCloud === value) {
  18167. return;
  18168. }
  18169. this._forcePointsCloud = value;
  18170. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18171. },
  18172. enumerable: true,
  18173. configurable: true
  18174. });
  18175. Object.defineProperty(Scene.prototype, "onDispose", {
  18176. /** A function to be executed when this scene is disposed. */
  18177. set: function (callback) {
  18178. if (this._onDisposeObserver) {
  18179. this.onDisposeObservable.remove(this._onDisposeObserver);
  18180. }
  18181. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18182. },
  18183. enumerable: true,
  18184. configurable: true
  18185. });
  18186. Object.defineProperty(Scene.prototype, "beforeRender", {
  18187. /** A function to be executed before rendering this scene */
  18188. set: function (callback) {
  18189. if (this._onBeforeRenderObserver) {
  18190. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  18191. }
  18192. if (callback) {
  18193. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  18194. }
  18195. },
  18196. enumerable: true,
  18197. configurable: true
  18198. });
  18199. Object.defineProperty(Scene.prototype, "afterRender", {
  18200. /** A function to be executed after rendering this scene */
  18201. set: function (callback) {
  18202. if (this._onAfterRenderObserver) {
  18203. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  18204. }
  18205. if (callback) {
  18206. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  18207. }
  18208. },
  18209. enumerable: true,
  18210. configurable: true
  18211. });
  18212. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  18213. set: function (callback) {
  18214. if (this._onBeforeCameraRenderObserver) {
  18215. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  18216. }
  18217. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  18218. },
  18219. enumerable: true,
  18220. configurable: true
  18221. });
  18222. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  18223. set: function (callback) {
  18224. if (this._onAfterCameraRenderObserver) {
  18225. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  18226. }
  18227. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  18228. },
  18229. enumerable: true,
  18230. configurable: true
  18231. });
  18232. Object.defineProperty(Scene.prototype, "gamepadManager", {
  18233. get: function () {
  18234. if (!this._gamepadManager) {
  18235. this._gamepadManager = new BABYLON.GamepadManager();
  18236. }
  18237. return this._gamepadManager;
  18238. },
  18239. enumerable: true,
  18240. configurable: true
  18241. });
  18242. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  18243. get: function () {
  18244. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  18245. },
  18246. enumerable: true,
  18247. configurable: true
  18248. });
  18249. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  18250. get: function () {
  18251. return this._useRightHandedSystem;
  18252. },
  18253. set: function (value) {
  18254. if (this._useRightHandedSystem === value) {
  18255. return;
  18256. }
  18257. this._useRightHandedSystem = value;
  18258. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18259. },
  18260. enumerable: true,
  18261. configurable: true
  18262. });
  18263. Scene.prototype.setStepId = function (newStepId) {
  18264. this._currentStepId = newStepId;
  18265. };
  18266. ;
  18267. Scene.prototype.getStepId = function () {
  18268. return this._currentStepId;
  18269. };
  18270. ;
  18271. Scene.prototype.getInternalStep = function () {
  18272. return this._currentInternalStep;
  18273. };
  18274. ;
  18275. Object.defineProperty(Scene.prototype, "fogEnabled", {
  18276. get: function () {
  18277. return this._fogEnabled;
  18278. },
  18279. /**
  18280. * is fog enabled on this scene.
  18281. */
  18282. set: function (value) {
  18283. if (this._fogEnabled === value) {
  18284. return;
  18285. }
  18286. this._fogEnabled = value;
  18287. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18288. },
  18289. enumerable: true,
  18290. configurable: true
  18291. });
  18292. Object.defineProperty(Scene.prototype, "fogMode", {
  18293. get: function () {
  18294. return this._fogMode;
  18295. },
  18296. set: function (value) {
  18297. if (this._fogMode === value) {
  18298. return;
  18299. }
  18300. this._fogMode = value;
  18301. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18302. },
  18303. enumerable: true,
  18304. configurable: true
  18305. });
  18306. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  18307. get: function () {
  18308. return this._shadowsEnabled;
  18309. },
  18310. set: function (value) {
  18311. if (this._shadowsEnabled === value) {
  18312. return;
  18313. }
  18314. this._shadowsEnabled = value;
  18315. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  18316. },
  18317. enumerable: true,
  18318. configurable: true
  18319. });
  18320. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  18321. get: function () {
  18322. return this._lightsEnabled;
  18323. },
  18324. set: function (value) {
  18325. if (this._lightsEnabled === value) {
  18326. return;
  18327. }
  18328. this._lightsEnabled = value;
  18329. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  18330. },
  18331. enumerable: true,
  18332. configurable: true
  18333. });
  18334. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  18335. /** The default material used on meshes when no material is affected */
  18336. get: function () {
  18337. if (!this._defaultMaterial) {
  18338. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  18339. }
  18340. return this._defaultMaterial;
  18341. },
  18342. /** The default material used on meshes when no material is affected */
  18343. set: function (value) {
  18344. this._defaultMaterial = value;
  18345. },
  18346. enumerable: true,
  18347. configurable: true
  18348. });
  18349. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  18350. get: function () {
  18351. return this._texturesEnabled;
  18352. },
  18353. set: function (value) {
  18354. if (this._texturesEnabled === value) {
  18355. return;
  18356. }
  18357. this._texturesEnabled = value;
  18358. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18359. },
  18360. enumerable: true,
  18361. configurable: true
  18362. });
  18363. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  18364. get: function () {
  18365. return this._skeletonsEnabled;
  18366. },
  18367. set: function (value) {
  18368. if (this._skeletonsEnabled === value) {
  18369. return;
  18370. }
  18371. this._skeletonsEnabled = value;
  18372. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  18373. },
  18374. enumerable: true,
  18375. configurable: true
  18376. });
  18377. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  18378. get: function () {
  18379. if (!this._postProcessRenderPipelineManager) {
  18380. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  18381. }
  18382. return this._postProcessRenderPipelineManager;
  18383. },
  18384. enumerable: true,
  18385. configurable: true
  18386. });
  18387. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  18388. get: function () {
  18389. if (!this._mainSoundTrack) {
  18390. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  18391. }
  18392. return this._mainSoundTrack;
  18393. },
  18394. enumerable: true,
  18395. configurable: true
  18396. });
  18397. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  18398. get: function () {
  18399. return this._alternateRendering;
  18400. },
  18401. enumerable: true,
  18402. configurable: true
  18403. });
  18404. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  18405. get: function () {
  18406. return this._frustumPlanes;
  18407. },
  18408. enumerable: true,
  18409. configurable: true
  18410. });
  18411. Object.defineProperty(Scene.prototype, "debugLayer", {
  18412. // Properties
  18413. get: function () {
  18414. if (!this._debugLayer) {
  18415. this._debugLayer = new BABYLON.DebugLayer(this);
  18416. }
  18417. return this._debugLayer;
  18418. },
  18419. enumerable: true,
  18420. configurable: true
  18421. });
  18422. Object.defineProperty(Scene.prototype, "workerCollisions", {
  18423. get: function () {
  18424. return this._workerCollisions;
  18425. },
  18426. set: function (enabled) {
  18427. if (!BABYLON.CollisionCoordinatorLegacy) {
  18428. return;
  18429. }
  18430. enabled = (enabled && !!Worker);
  18431. this._workerCollisions = enabled;
  18432. if (this.collisionCoordinator) {
  18433. this.collisionCoordinator.destroy();
  18434. }
  18435. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  18436. this.collisionCoordinator.init(this);
  18437. },
  18438. enumerable: true,
  18439. configurable: true
  18440. });
  18441. Object.defineProperty(Scene.prototype, "selectionOctree", {
  18442. get: function () {
  18443. return this._selectionOctree;
  18444. },
  18445. enumerable: true,
  18446. configurable: true
  18447. });
  18448. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  18449. /**
  18450. * The mesh that is currently under the pointer.
  18451. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  18452. */
  18453. get: function () {
  18454. return this._pointerOverMesh;
  18455. },
  18456. enumerable: true,
  18457. configurable: true
  18458. });
  18459. Object.defineProperty(Scene.prototype, "pointerX", {
  18460. /**
  18461. * Current on-screen X position of the pointer
  18462. * @return {number} X position of the pointer
  18463. */
  18464. get: function () {
  18465. return this._pointerX;
  18466. },
  18467. enumerable: true,
  18468. configurable: true
  18469. });
  18470. Object.defineProperty(Scene.prototype, "pointerY", {
  18471. /**
  18472. * Current on-screen Y position of the pointer
  18473. * @return {number} Y position of the pointer
  18474. */
  18475. get: function () {
  18476. return this._pointerY;
  18477. },
  18478. enumerable: true,
  18479. configurable: true
  18480. });
  18481. Scene.prototype.getCachedMaterial = function () {
  18482. return this._cachedMaterial;
  18483. };
  18484. Scene.prototype.getCachedEffect = function () {
  18485. return this._cachedEffect;
  18486. };
  18487. Scene.prototype.getCachedVisibility = function () {
  18488. return this._cachedVisibility;
  18489. };
  18490. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  18491. if (visibility === void 0) { visibility = 1; }
  18492. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  18493. };
  18494. Scene.prototype.getBoundingBoxRenderer = function () {
  18495. if (!this._boundingBoxRenderer) {
  18496. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  18497. }
  18498. return this._boundingBoxRenderer;
  18499. };
  18500. Scene.prototype.getOutlineRenderer = function () {
  18501. return this._outlineRenderer;
  18502. };
  18503. Scene.prototype.getEngine = function () {
  18504. return this._engine;
  18505. };
  18506. Scene.prototype.getTotalVertices = function () {
  18507. return this._totalVertices.current;
  18508. };
  18509. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  18510. get: function () {
  18511. return this._totalVertices;
  18512. },
  18513. enumerable: true,
  18514. configurable: true
  18515. });
  18516. Scene.prototype.getActiveIndices = function () {
  18517. return this._activeIndices.current;
  18518. };
  18519. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  18520. get: function () {
  18521. return this._activeIndices;
  18522. },
  18523. enumerable: true,
  18524. configurable: true
  18525. });
  18526. Scene.prototype.getActiveParticles = function () {
  18527. return this._activeParticles.current;
  18528. };
  18529. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  18530. get: function () {
  18531. return this._activeParticles;
  18532. },
  18533. enumerable: true,
  18534. configurable: true
  18535. });
  18536. Scene.prototype.getActiveBones = function () {
  18537. return this._activeBones.current;
  18538. };
  18539. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  18540. get: function () {
  18541. return this._activeBones;
  18542. },
  18543. enumerable: true,
  18544. configurable: true
  18545. });
  18546. // Stats
  18547. Scene.prototype.getInterFramePerfCounter = function () {
  18548. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18549. return 0;
  18550. };
  18551. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  18552. get: function () {
  18553. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18554. return null;
  18555. },
  18556. enumerable: true,
  18557. configurable: true
  18558. });
  18559. Scene.prototype.getLastFrameDuration = function () {
  18560. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  18561. return 0;
  18562. };
  18563. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  18564. get: function () {
  18565. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18566. return null;
  18567. },
  18568. enumerable: true,
  18569. configurable: true
  18570. });
  18571. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  18572. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  18573. return 0;
  18574. };
  18575. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  18576. get: function () {
  18577. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18578. return null;
  18579. },
  18580. enumerable: true,
  18581. configurable: true
  18582. });
  18583. Scene.prototype.getActiveMeshes = function () {
  18584. return this._activeMeshes;
  18585. };
  18586. Scene.prototype.getRenderTargetsDuration = function () {
  18587. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  18588. return 0;
  18589. };
  18590. Scene.prototype.getRenderDuration = function () {
  18591. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  18592. return 0;
  18593. };
  18594. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  18595. get: function () {
  18596. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18597. return null;
  18598. },
  18599. enumerable: true,
  18600. configurable: true
  18601. });
  18602. Scene.prototype.getParticlesDuration = function () {
  18603. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  18604. return 0;
  18605. };
  18606. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  18607. get: function () {
  18608. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18609. return null;
  18610. },
  18611. enumerable: true,
  18612. configurable: true
  18613. });
  18614. Scene.prototype.getSpritesDuration = function () {
  18615. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  18616. return 0;
  18617. };
  18618. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  18619. get: function () {
  18620. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  18621. return null;
  18622. },
  18623. enumerable: true,
  18624. configurable: true
  18625. });
  18626. Scene.prototype.getAnimationRatio = function () {
  18627. return this._animationRatio;
  18628. };
  18629. Scene.prototype.getRenderId = function () {
  18630. return this._renderId;
  18631. };
  18632. Scene.prototype.incrementRenderId = function () {
  18633. this._renderId++;
  18634. };
  18635. Scene.prototype._updatePointerPosition = function (evt) {
  18636. var canvasRect = this._engine.getRenderingCanvasClientRect();
  18637. if (!canvasRect) {
  18638. return;
  18639. }
  18640. this._pointerX = evt.clientX - canvasRect.left;
  18641. this._pointerY = evt.clientY - canvasRect.top;
  18642. this._unTranslatedPointerX = this._pointerX;
  18643. this._unTranslatedPointerY = this._pointerY;
  18644. };
  18645. Scene.prototype._createUbo = function () {
  18646. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18647. this._sceneUbo.addUniform("viewProjection", 16);
  18648. this._sceneUbo.addUniform("view", 16);
  18649. };
  18650. Scene.prototype._createAlternateUbo = function () {
  18651. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18652. this._alternateSceneUbo.addUniform("viewProjection", 16);
  18653. this._alternateSceneUbo.addUniform("view", 16);
  18654. };
  18655. // Pointers handling
  18656. /**
  18657. * Use this method to simulate a pointer move on a mesh
  18658. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18659. */
  18660. Scene.prototype.simulatePointerMove = function (pickResult) {
  18661. var evt = new PointerEvent("pointermove");
  18662. return this._processPointerMove(pickResult, evt);
  18663. };
  18664. Scene.prototype._processPointerMove = function (pickResult, evt) {
  18665. var canvas = this._engine.getRenderingCanvas();
  18666. if (!canvas) {
  18667. return this;
  18668. }
  18669. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18670. this.setPointerOverSprite(null);
  18671. this.setPointerOverMesh(pickResult.pickedMesh);
  18672. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  18673. if (this._pointerOverMesh.actionManager.hoverCursor) {
  18674. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  18675. }
  18676. else {
  18677. canvas.style.cursor = this.hoverCursor;
  18678. }
  18679. }
  18680. else {
  18681. canvas.style.cursor = this.defaultCursor;
  18682. }
  18683. }
  18684. else {
  18685. this.setPointerOverMesh(null);
  18686. // Sprites
  18687. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  18688. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  18689. this.setPointerOverSprite(pickResult.pickedSprite);
  18690. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  18691. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  18692. }
  18693. else {
  18694. canvas.style.cursor = this.hoverCursor;
  18695. }
  18696. }
  18697. else {
  18698. this.setPointerOverSprite(null);
  18699. // Restore pointer
  18700. canvas.style.cursor = this.defaultCursor;
  18701. }
  18702. }
  18703. if (pickResult) {
  18704. if (this.onPointerMove) {
  18705. this.onPointerMove(evt, pickResult);
  18706. }
  18707. if (this.onPointerObservable.hasObservers()) {
  18708. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  18709. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18710. this.onPointerObservable.notifyObservers(pi, type);
  18711. }
  18712. }
  18713. return this;
  18714. };
  18715. /**
  18716. * Use this method to simulate a pointer down on a mesh
  18717. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18718. */
  18719. Scene.prototype.simulatePointerDown = function (pickResult) {
  18720. var evt = new PointerEvent("pointerdown");
  18721. return this._processPointerDown(pickResult, evt);
  18722. };
  18723. Scene.prototype._processPointerDown = function (pickResult, evt) {
  18724. var _this = this;
  18725. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18726. this._pickedDownMesh = pickResult.pickedMesh;
  18727. var actionManager = pickResult.pickedMesh.actionManager;
  18728. if (actionManager) {
  18729. if (actionManager.hasPickTriggers) {
  18730. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18731. switch (evt.button) {
  18732. case 0:
  18733. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18734. break;
  18735. case 1:
  18736. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18737. break;
  18738. case 2:
  18739. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18740. break;
  18741. }
  18742. }
  18743. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  18744. window.setTimeout(function () {
  18745. 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);
  18746. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  18747. if (_this._totalPointersPressed !== 0 &&
  18748. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  18749. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  18750. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  18751. _this._startingPointerTime = 0;
  18752. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18753. }
  18754. }
  18755. }, Scene.LongPressDelay);
  18756. }
  18757. }
  18758. }
  18759. if (pickResult) {
  18760. if (this.onPointerDown) {
  18761. this.onPointerDown(evt, pickResult);
  18762. }
  18763. if (this.onPointerObservable.hasObservers()) {
  18764. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  18765. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18766. this.onPointerObservable.notifyObservers(pi, type);
  18767. }
  18768. }
  18769. return this;
  18770. };
  18771. /**
  18772. * Use this method to simulate a pointer up on a mesh
  18773. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18774. */
  18775. Scene.prototype.simulatePointerUp = function (pickResult) {
  18776. var evt = new PointerEvent("pointerup");
  18777. var clickInfo = new ClickInfo();
  18778. clickInfo.singleClick = true;
  18779. return this._processPointerUp(pickResult, evt, clickInfo);
  18780. };
  18781. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  18782. if (pickResult && pickResult && pickResult.pickedMesh) {
  18783. this._pickedUpMesh = pickResult.pickedMesh;
  18784. if (this._pickedDownMesh === this._pickedUpMesh) {
  18785. if (this.onPointerPick) {
  18786. this.onPointerPick(evt, pickResult);
  18787. }
  18788. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  18789. var type = BABYLON.PointerEventTypes.POINTERPICK;
  18790. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18791. this.onPointerObservable.notifyObservers(pi, type);
  18792. }
  18793. }
  18794. if (pickResult.pickedMesh.actionManager) {
  18795. if (clickInfo.ignore) {
  18796. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18797. }
  18798. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  18799. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18800. }
  18801. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18802. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18803. }
  18804. }
  18805. }
  18806. if (this._pickedDownMesh &&
  18807. this._pickedDownMesh.actionManager &&
  18808. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  18809. this._pickedDownMesh !== this._pickedUpMesh) {
  18810. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  18811. }
  18812. if (this.onPointerUp) {
  18813. this.onPointerUp(evt, pickResult);
  18814. }
  18815. if (this.onPointerObservable.hasObservers()) {
  18816. if (!clickInfo.ignore) {
  18817. if (!clickInfo.hasSwiped) {
  18818. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  18819. var type = BABYLON.PointerEventTypes.POINTERTAP;
  18820. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18821. this.onPointerObservable.notifyObservers(pi, type);
  18822. }
  18823. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  18824. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  18825. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18826. this.onPointerObservable.notifyObservers(pi, type);
  18827. }
  18828. }
  18829. }
  18830. else {
  18831. var type = BABYLON.PointerEventTypes.POINTERUP;
  18832. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18833. this.onPointerObservable.notifyObservers(pi, type);
  18834. }
  18835. }
  18836. return this;
  18837. };
  18838. /**
  18839. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  18840. * @param attachUp defines if you want to attach events to pointerup
  18841. * @param attachDown defines if you want to attach events to pointerdown
  18842. * @param attachMove defines if you want to attach events to pointermove
  18843. */
  18844. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  18845. var _this = this;
  18846. if (attachUp === void 0) { attachUp = true; }
  18847. if (attachDown === void 0) { attachDown = true; }
  18848. if (attachMove === void 0) { attachMove = true; }
  18849. this._initActionManager = function (act, clickInfo) {
  18850. if (!_this._meshPickProceed) {
  18851. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18852. _this._currentPickResult = pickResult;
  18853. if (pickResult) {
  18854. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  18855. }
  18856. _this._meshPickProceed = true;
  18857. }
  18858. return act;
  18859. };
  18860. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  18861. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  18862. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  18863. btn !== _this._previousButtonPressed) {
  18864. _this._doubleClickOccured = false;
  18865. clickInfo.singleClick = true;
  18866. clickInfo.ignore = false;
  18867. cb(clickInfo, _this._currentPickResult);
  18868. }
  18869. };
  18870. this._initClickEvent = function (obs1, obs2, evt, cb) {
  18871. var clickInfo = new ClickInfo();
  18872. _this._currentPickResult = null;
  18873. var act = null;
  18874. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  18875. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  18876. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18877. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  18878. act = _this._initActionManager(act, clickInfo);
  18879. if (act)
  18880. checkPicking = act.hasPickTriggers;
  18881. }
  18882. if (checkPicking) {
  18883. var btn = evt.button;
  18884. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  18885. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  18886. if (!clickInfo.hasSwiped) {
  18887. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  18888. if (!checkSingleClickImmediately) {
  18889. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  18890. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18891. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18892. act = _this._initActionManager(act, clickInfo);
  18893. if (act)
  18894. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  18895. }
  18896. }
  18897. if (checkSingleClickImmediately) {
  18898. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  18899. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  18900. btn !== _this._previousButtonPressed) {
  18901. clickInfo.singleClick = true;
  18902. cb(clickInfo, _this._currentPickResult);
  18903. }
  18904. }
  18905. else {
  18906. // wait that no double click has been raised during the double click delay
  18907. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18908. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  18909. }
  18910. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  18911. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18912. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18913. act = _this._initActionManager(act, clickInfo);
  18914. if (act)
  18915. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  18916. }
  18917. if (checkDoubleClick) {
  18918. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  18919. if (btn === _this._previousButtonPressed &&
  18920. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  18921. !_this._doubleClickOccured) {
  18922. // pointer has not moved for 2 clicks, it's a double click
  18923. if (!clickInfo.hasSwiped &&
  18924. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  18925. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  18926. _this._previousStartingPointerTime = 0;
  18927. _this._doubleClickOccured = true;
  18928. clickInfo.doubleClick = true;
  18929. clickInfo.ignore = false;
  18930. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  18931. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  18932. }
  18933. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18934. cb(clickInfo, _this._currentPickResult);
  18935. }
  18936. else {
  18937. _this._doubleClickOccured = false;
  18938. _this._previousStartingPointerTime = _this._startingPointerTime;
  18939. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  18940. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  18941. _this._previousButtonPressed = btn;
  18942. if (Scene.ExclusiveDoubleClickMode) {
  18943. if (_this._previousDelayedSimpleClickTimeout) {
  18944. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  18945. }
  18946. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18947. cb(clickInfo, _this._previousPickResult);
  18948. }
  18949. else {
  18950. cb(clickInfo, _this._currentPickResult);
  18951. }
  18952. }
  18953. }
  18954. else {
  18955. _this._doubleClickOccured = false;
  18956. _this._previousStartingPointerTime = _this._startingPointerTime;
  18957. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  18958. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  18959. _this._previousButtonPressed = btn;
  18960. }
  18961. }
  18962. }
  18963. }
  18964. clickInfo.ignore = true;
  18965. cb(clickInfo, _this._currentPickResult);
  18966. };
  18967. this._spritePredicate = function (sprite) {
  18968. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  18969. };
  18970. this._onPointerMove = function (evt) {
  18971. _this._updatePointerPosition(evt);
  18972. // PreObservable support
  18973. if (_this.onPrePointerObservable.hasObservers()) {
  18974. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  18975. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18976. _this.onPrePointerObservable.notifyObservers(pi, type);
  18977. if (pi.skipOnPointerObservable) {
  18978. return;
  18979. }
  18980. }
  18981. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18982. return;
  18983. }
  18984. if (!_this.pointerMovePredicate) {
  18985. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  18986. }
  18987. // Meshes
  18988. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  18989. _this._processPointerMove(pickResult, evt);
  18990. };
  18991. this._onPointerDown = function (evt) {
  18992. _this._totalPointersPressed++;
  18993. _this._pickedDownMesh = null;
  18994. _this._meshPickProceed = false;
  18995. _this._updatePointerPosition(evt);
  18996. if (_this.preventDefaultOnPointerDown && canvas) {
  18997. evt.preventDefault();
  18998. canvas.focus();
  18999. }
  19000. // PreObservable support
  19001. if (_this.onPrePointerObservable.hasObservers()) {
  19002. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  19003. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19004. _this.onPrePointerObservable.notifyObservers(pi, type);
  19005. if (pi.skipOnPointerObservable) {
  19006. return;
  19007. }
  19008. }
  19009. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19010. return;
  19011. }
  19012. _this._startingPointerPosition.x = _this._pointerX;
  19013. _this._startingPointerPosition.y = _this._pointerY;
  19014. _this._startingPointerTime = new Date().getTime();
  19015. if (!_this.pointerDownPredicate) {
  19016. _this.pointerDownPredicate = function (mesh) {
  19017. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  19018. };
  19019. }
  19020. // Meshes
  19021. _this._pickedDownMesh = null;
  19022. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  19023. _this._processPointerDown(pickResult, evt);
  19024. // Sprites
  19025. _this._pickedDownSprite = null;
  19026. if (_this.spriteManagers.length > 0) {
  19027. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  19028. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  19029. if (pickResult.pickedSprite.actionManager) {
  19030. _this._pickedDownSprite = pickResult.pickedSprite;
  19031. switch (evt.button) {
  19032. case 0:
  19033. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19034. break;
  19035. case 1:
  19036. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19037. break;
  19038. case 2:
  19039. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19040. break;
  19041. }
  19042. if (pickResult.pickedSprite.actionManager) {
  19043. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19044. }
  19045. }
  19046. }
  19047. }
  19048. };
  19049. this._onPointerUp = function (evt) {
  19050. if (_this._totalPointersPressed === 0) {
  19051. return; // So we need to test it the pointer down was pressed before.
  19052. }
  19053. _this._totalPointersPressed--;
  19054. _this._pickedUpMesh = null;
  19055. _this._meshPickProceed = false;
  19056. _this._updatePointerPosition(evt);
  19057. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  19058. // PreObservable support
  19059. if (_this.onPrePointerObservable.hasObservers()) {
  19060. if (!clickInfo.ignore) {
  19061. if (!clickInfo.hasSwiped) {
  19062. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  19063. var type = BABYLON.PointerEventTypes.POINTERTAP;
  19064. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19065. _this.onPrePointerObservable.notifyObservers(pi, type);
  19066. if (pi.skipOnPointerObservable) {
  19067. return;
  19068. }
  19069. }
  19070. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  19071. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  19072. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19073. _this.onPrePointerObservable.notifyObservers(pi, type);
  19074. if (pi.skipOnPointerObservable) {
  19075. return;
  19076. }
  19077. }
  19078. }
  19079. }
  19080. else {
  19081. var type = BABYLON.PointerEventTypes.POINTERUP;
  19082. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19083. _this.onPrePointerObservable.notifyObservers(pi, type);
  19084. if (pi.skipOnPointerObservable) {
  19085. return;
  19086. }
  19087. }
  19088. }
  19089. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19090. return;
  19091. }
  19092. if (!_this.pointerUpPredicate) {
  19093. _this.pointerUpPredicate = function (mesh) {
  19094. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  19095. };
  19096. }
  19097. // Meshes
  19098. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  19099. _this._initActionManager(null, clickInfo);
  19100. }
  19101. if (!pickResult) {
  19102. pickResult = _this._currentPickResult;
  19103. }
  19104. _this._processPointerUp(pickResult, evt, clickInfo);
  19105. // Sprites
  19106. if (_this.spriteManagers.length > 0) {
  19107. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  19108. if (spritePickResult) {
  19109. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  19110. if (spritePickResult.pickedSprite.actionManager) {
  19111. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  19112. if (spritePickResult.pickedSprite.actionManager) {
  19113. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  19114. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  19115. }
  19116. }
  19117. }
  19118. }
  19119. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  19120. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  19121. }
  19122. }
  19123. }
  19124. _this._previousPickResult = _this._currentPickResult;
  19125. });
  19126. };
  19127. this._onKeyDown = function (evt) {
  19128. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  19129. if (_this.onPreKeyboardObservable.hasObservers()) {
  19130. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  19131. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  19132. if (pi.skipOnPointerObservable) {
  19133. return;
  19134. }
  19135. }
  19136. if (_this.onKeyboardObservable.hasObservers()) {
  19137. var pi = new BABYLON.KeyboardInfo(type, evt);
  19138. _this.onKeyboardObservable.notifyObservers(pi, type);
  19139. }
  19140. if (_this.actionManager) {
  19141. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  19142. }
  19143. };
  19144. this._onKeyUp = function (evt) {
  19145. var type = BABYLON.KeyboardEventTypes.KEYUP;
  19146. if (_this.onPreKeyboardObservable.hasObservers()) {
  19147. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  19148. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  19149. if (pi.skipOnPointerObservable) {
  19150. return;
  19151. }
  19152. }
  19153. if (_this.onKeyboardObservable.hasObservers()) {
  19154. var pi = new BABYLON.KeyboardInfo(type, evt);
  19155. _this.onKeyboardObservable.notifyObservers(pi, type);
  19156. }
  19157. if (_this.actionManager) {
  19158. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  19159. }
  19160. };
  19161. var engine = this.getEngine();
  19162. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  19163. if (!canvas) {
  19164. return;
  19165. }
  19166. canvas.addEventListener("keydown", _this._onKeyDown, false);
  19167. canvas.addEventListener("keyup", _this._onKeyUp, false);
  19168. });
  19169. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  19170. if (!canvas) {
  19171. return;
  19172. }
  19173. canvas.removeEventListener("keydown", _this._onKeyDown);
  19174. canvas.removeEventListener("keyup", _this._onKeyUp);
  19175. });
  19176. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  19177. var canvas = this._engine.getRenderingCanvas();
  19178. if (!canvas) {
  19179. return;
  19180. }
  19181. if (attachMove) {
  19182. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  19183. // Wheel
  19184. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  19185. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  19186. }
  19187. if (attachDown) {
  19188. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  19189. }
  19190. if (attachUp) {
  19191. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  19192. }
  19193. canvas.tabIndex = 1;
  19194. };
  19195. Scene.prototype.detachControl = function () {
  19196. var engine = this.getEngine();
  19197. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  19198. var canvas = engine.getRenderingCanvas();
  19199. if (!canvas) {
  19200. return;
  19201. }
  19202. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  19203. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  19204. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  19205. if (this._onCanvasBlurObserver) {
  19206. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  19207. }
  19208. if (this._onCanvasFocusObserver) {
  19209. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  19210. }
  19211. // Wheel
  19212. canvas.removeEventListener('mousewheel', this._onPointerMove);
  19213. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  19214. // Keyboard
  19215. canvas.removeEventListener("keydown", this._onKeyDown);
  19216. canvas.removeEventListener("keyup", this._onKeyUp);
  19217. // Observables
  19218. this.onKeyboardObservable.clear();
  19219. this.onPreKeyboardObservable.clear();
  19220. this.onPointerObservable.clear();
  19221. this.onPrePointerObservable.clear();
  19222. };
  19223. // Ready
  19224. Scene.prototype.isReady = function () {
  19225. if (this._isDisposed) {
  19226. return false;
  19227. }
  19228. if (this._pendingData.length > 0) {
  19229. return false;
  19230. }
  19231. var index;
  19232. // Geometries
  19233. for (index = 0; index < this._geometries.length; index++) {
  19234. var geometry = this._geometries[index];
  19235. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19236. return false;
  19237. }
  19238. }
  19239. // Meshes
  19240. for (index = 0; index < this.meshes.length; index++) {
  19241. var mesh = this.meshes[index];
  19242. if (!mesh.isEnabled()) {
  19243. continue;
  19244. }
  19245. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  19246. continue;
  19247. }
  19248. if (!mesh.isReady()) {
  19249. return false;
  19250. }
  19251. var mat = mesh.material;
  19252. if (mat) {
  19253. if (!mat.isReady(mesh)) {
  19254. return false;
  19255. }
  19256. }
  19257. }
  19258. return true;
  19259. };
  19260. Scene.prototype.resetCachedMaterial = function () {
  19261. this._cachedMaterial = null;
  19262. this._cachedEffect = null;
  19263. this._cachedVisibility = null;
  19264. };
  19265. Scene.prototype.registerBeforeRender = function (func) {
  19266. this.onBeforeRenderObservable.add(func);
  19267. };
  19268. Scene.prototype.unregisterBeforeRender = function (func) {
  19269. this.onBeforeRenderObservable.removeCallback(func);
  19270. };
  19271. Scene.prototype.registerAfterRender = function (func) {
  19272. this.onAfterRenderObservable.add(func);
  19273. };
  19274. Scene.prototype.unregisterAfterRender = function (func) {
  19275. this.onAfterRenderObservable.removeCallback(func);
  19276. };
  19277. Scene.prototype._addPendingData = function (data) {
  19278. this._pendingData.push(data);
  19279. };
  19280. Scene.prototype._removePendingData = function (data) {
  19281. var wasLoading = this.isLoading;
  19282. var index = this._pendingData.indexOf(data);
  19283. if (index !== -1) {
  19284. this._pendingData.splice(index, 1);
  19285. }
  19286. if (wasLoading && !this.isLoading) {
  19287. this.onDataLoadedObservable.notifyObservers(this);
  19288. }
  19289. };
  19290. Scene.prototype.getWaitingItemsCount = function () {
  19291. return this._pendingData.length;
  19292. };
  19293. Object.defineProperty(Scene.prototype, "isLoading", {
  19294. get: function () {
  19295. return this._pendingData.length > 0;
  19296. },
  19297. enumerable: true,
  19298. configurable: true
  19299. });
  19300. /**
  19301. * Registers a function to be executed when the scene is ready.
  19302. * @param {Function} func - the function to be executed.
  19303. */
  19304. Scene.prototype.executeWhenReady = function (func) {
  19305. var _this = this;
  19306. this.onReadyObservable.add(func);
  19307. if (this._executeWhenReadyTimeoutId !== -1) {
  19308. return;
  19309. }
  19310. this._executeWhenReadyTimeoutId = setTimeout(function () {
  19311. _this._checkIsReady();
  19312. }, 150);
  19313. };
  19314. Scene.prototype._checkIsReady = function () {
  19315. var _this = this;
  19316. if (this.isReady()) {
  19317. this.onReadyObservable.notifyObservers(this);
  19318. this.onReadyObservable.clear();
  19319. this._executeWhenReadyTimeoutId = -1;
  19320. return;
  19321. }
  19322. this._executeWhenReadyTimeoutId = setTimeout(function () {
  19323. _this._checkIsReady();
  19324. }, 150);
  19325. };
  19326. // Animations
  19327. /**
  19328. * Will start the animation sequence of a given target
  19329. * @param target - the target
  19330. * @param {number} from - from which frame should animation start
  19331. * @param {number} to - till which frame should animation run.
  19332. * @param {boolean} [loop] - should the animation loop
  19333. * @param {number} [speedRatio] - the speed in which to run the animation
  19334. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  19335. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  19336. * Returns {BABYLON.Animatable} the animatable object created for this animation
  19337. * See BABYLON.Animatable
  19338. */
  19339. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  19340. if (speedRatio === void 0) { speedRatio = 1.0; }
  19341. if (from > to && speedRatio > 0) {
  19342. speedRatio *= -1;
  19343. }
  19344. this.stopAnimation(target);
  19345. if (!animatable) {
  19346. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  19347. }
  19348. // Local animations
  19349. if (target.animations) {
  19350. animatable.appendAnimations(target, target.animations);
  19351. }
  19352. // Children animations
  19353. if (target.getAnimatables) {
  19354. var animatables = target.getAnimatables();
  19355. for (var index = 0; index < animatables.length; index++) {
  19356. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  19357. }
  19358. }
  19359. animatable.reset();
  19360. return animatable;
  19361. };
  19362. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  19363. if (speedRatio === undefined) {
  19364. speedRatio = 1.0;
  19365. }
  19366. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  19367. return animatable;
  19368. };
  19369. Scene.prototype.getAnimatableByTarget = function (target) {
  19370. for (var index = 0; index < this._activeAnimatables.length; index++) {
  19371. if (this._activeAnimatables[index].target === target) {
  19372. return this._activeAnimatables[index];
  19373. }
  19374. }
  19375. return null;
  19376. };
  19377. Object.defineProperty(Scene.prototype, "Animatables", {
  19378. get: function () {
  19379. return this._activeAnimatables;
  19380. },
  19381. enumerable: true,
  19382. configurable: true
  19383. });
  19384. /**
  19385. * Will stop the animation of the given target
  19386. * @param target - the target
  19387. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  19388. * @see beginAnimation
  19389. */
  19390. Scene.prototype.stopAnimation = function (target, animationName) {
  19391. var animatable = this.getAnimatableByTarget(target);
  19392. if (animatable) {
  19393. animatable.stop(animationName);
  19394. }
  19395. };
  19396. /**
  19397. * Stops and removes all animations that have been applied to the scene
  19398. */
  19399. Scene.prototype.stopAllAnimations = function () {
  19400. if (this._activeAnimatables) {
  19401. for (var i = 0; i < this._activeAnimatables.length; i++) {
  19402. this._activeAnimatables[i].stop();
  19403. }
  19404. this._activeAnimatables = [];
  19405. }
  19406. };
  19407. Scene.prototype._animate = function () {
  19408. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  19409. return;
  19410. }
  19411. // Getting time
  19412. var now = BABYLON.Tools.Now;
  19413. if (!this._animationTimeLast) {
  19414. if (this._pendingData.length > 0) {
  19415. return;
  19416. }
  19417. this._animationTimeLast = now;
  19418. }
  19419. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  19420. this._animationTime += deltaTime;
  19421. this._animationTimeLast = now;
  19422. for (var index = 0; index < this._activeAnimatables.length; index++) {
  19423. this._activeAnimatables[index]._animate(this._animationTime);
  19424. }
  19425. };
  19426. // Matrix
  19427. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  19428. this._useAlternateCameraConfiguration = active;
  19429. };
  19430. Scene.prototype.getViewMatrix = function () {
  19431. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  19432. };
  19433. Scene.prototype.getProjectionMatrix = function () {
  19434. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  19435. };
  19436. Scene.prototype.getTransformMatrix = function () {
  19437. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  19438. };
  19439. Scene.prototype.setTransformMatrix = function (view, projection) {
  19440. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  19441. return;
  19442. }
  19443. this._viewUpdateFlag = view.updateFlag;
  19444. this._projectionUpdateFlag = projection.updateFlag;
  19445. this._viewMatrix = view;
  19446. this._projectionMatrix = projection;
  19447. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  19448. // Update frustum
  19449. if (!this._frustumPlanes) {
  19450. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  19451. }
  19452. else {
  19453. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  19454. }
  19455. if (this.activeCamera && this.activeCamera._alternateCamera) {
  19456. var otherCamera = this.activeCamera._alternateCamera;
  19457. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  19458. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  19459. }
  19460. if (this._sceneUbo.useUbo) {
  19461. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  19462. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  19463. this._sceneUbo.update();
  19464. }
  19465. };
  19466. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  19467. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  19468. return;
  19469. }
  19470. this._alternateViewUpdateFlag = view.updateFlag;
  19471. this._alternateProjectionUpdateFlag = projection.updateFlag;
  19472. this._alternateViewMatrix = view;
  19473. this._alternateProjectionMatrix = projection;
  19474. if (!this._alternateTransformMatrix) {
  19475. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  19476. }
  19477. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  19478. if (!this._alternateSceneUbo) {
  19479. this._createAlternateUbo();
  19480. }
  19481. if (this._alternateSceneUbo.useUbo) {
  19482. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  19483. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  19484. this._alternateSceneUbo.update();
  19485. }
  19486. };
  19487. Scene.prototype.getSceneUniformBuffer = function () {
  19488. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  19489. };
  19490. // Methods
  19491. Scene.prototype.getUniqueId = function () {
  19492. var result = Scene._uniqueIdCounter;
  19493. Scene._uniqueIdCounter++;
  19494. return result;
  19495. };
  19496. Scene.prototype.addMesh = function (newMesh) {
  19497. this.meshes.push(newMesh);
  19498. //notify the collision coordinator
  19499. if (this.collisionCoordinator) {
  19500. this.collisionCoordinator.onMeshAdded(newMesh);
  19501. }
  19502. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  19503. };
  19504. Scene.prototype.removeMesh = function (toRemove) {
  19505. var index = this.meshes.indexOf(toRemove);
  19506. if (index !== -1) {
  19507. // Remove from the scene if mesh found
  19508. this.meshes.splice(index, 1);
  19509. }
  19510. this.onMeshRemovedObservable.notifyObservers(toRemove);
  19511. return index;
  19512. };
  19513. Scene.prototype.addTransformNode = function (newTransformNode) {
  19514. this.transformNodes.push(newTransformNode);
  19515. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  19516. };
  19517. Scene.prototype.removeTransformNode = function (toRemove) {
  19518. var index = this.transformNodes.indexOf(toRemove);
  19519. if (index !== -1) {
  19520. // Remove from the scene if found
  19521. this.transformNodes.splice(index, 1);
  19522. }
  19523. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  19524. return index;
  19525. };
  19526. Scene.prototype.removeSkeleton = function (toRemove) {
  19527. var index = this.skeletons.indexOf(toRemove);
  19528. if (index !== -1) {
  19529. // Remove from the scene if found
  19530. this.skeletons.splice(index, 1);
  19531. }
  19532. return index;
  19533. };
  19534. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  19535. var index = this.morphTargetManagers.indexOf(toRemove);
  19536. if (index !== -1) {
  19537. // Remove from the scene if found
  19538. this.morphTargetManagers.splice(index, 1);
  19539. }
  19540. return index;
  19541. };
  19542. Scene.prototype.removeLight = function (toRemove) {
  19543. var index = this.lights.indexOf(toRemove);
  19544. if (index !== -1) {
  19545. // Remove from the scene if mesh found
  19546. this.lights.splice(index, 1);
  19547. this.sortLightsByPriority();
  19548. }
  19549. this.onLightRemovedObservable.notifyObservers(toRemove);
  19550. return index;
  19551. };
  19552. Scene.prototype.removeCamera = function (toRemove) {
  19553. var index = this.cameras.indexOf(toRemove);
  19554. if (index !== -1) {
  19555. // Remove from the scene if mesh found
  19556. this.cameras.splice(index, 1);
  19557. }
  19558. // Remove from activeCameras
  19559. var index2 = this.activeCameras.indexOf(toRemove);
  19560. if (index2 !== -1) {
  19561. // Remove from the scene if mesh found
  19562. this.activeCameras.splice(index2, 1);
  19563. }
  19564. // Reset the activeCamera
  19565. if (this.activeCamera === toRemove) {
  19566. if (this.cameras.length > 0) {
  19567. this.activeCamera = this.cameras[0];
  19568. }
  19569. else {
  19570. this.activeCamera = null;
  19571. }
  19572. }
  19573. this.onCameraRemovedObservable.notifyObservers(toRemove);
  19574. return index;
  19575. };
  19576. Scene.prototype.addLight = function (newLight) {
  19577. this.lights.push(newLight);
  19578. this.sortLightsByPriority();
  19579. this.onNewLightAddedObservable.notifyObservers(newLight);
  19580. };
  19581. Scene.prototype.sortLightsByPriority = function () {
  19582. if (this.requireLightSorting) {
  19583. this.lights.sort(BABYLON.Light.compareLightsPriority);
  19584. }
  19585. };
  19586. Scene.prototype.addCamera = function (newCamera) {
  19587. this.cameras.push(newCamera);
  19588. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  19589. };
  19590. /**
  19591. * Switch active camera
  19592. * @param {Camera} newCamera - new active camera
  19593. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  19594. */
  19595. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  19596. if (attachControl === void 0) { attachControl = true; }
  19597. var canvas = this._engine.getRenderingCanvas();
  19598. if (!canvas) {
  19599. return;
  19600. }
  19601. if (this.activeCamera) {
  19602. this.activeCamera.detachControl(canvas);
  19603. }
  19604. this.activeCamera = newCamera;
  19605. if (attachControl) {
  19606. newCamera.attachControl(canvas);
  19607. }
  19608. };
  19609. /**
  19610. * sets the active camera of the scene using its ID
  19611. * @param {string} id - the camera's ID
  19612. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19613. * @see activeCamera
  19614. */
  19615. Scene.prototype.setActiveCameraByID = function (id) {
  19616. var camera = this.getCameraByID(id);
  19617. if (camera) {
  19618. this.activeCamera = camera;
  19619. return camera;
  19620. }
  19621. return null;
  19622. };
  19623. /**
  19624. * sets the active camera of the scene using its name
  19625. * @param {string} name - the camera's name
  19626. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19627. * @see activeCamera
  19628. */
  19629. Scene.prototype.setActiveCameraByName = function (name) {
  19630. var camera = this.getCameraByName(name);
  19631. if (camera) {
  19632. this.activeCamera = camera;
  19633. return camera;
  19634. }
  19635. return null;
  19636. };
  19637. /**
  19638. * get a material using its id
  19639. * @param {string} the material's ID
  19640. * @return {BABYLON.Material|null} the material or null if none found.
  19641. */
  19642. Scene.prototype.getMaterialByID = function (id) {
  19643. for (var index = 0; index < this.materials.length; index++) {
  19644. if (this.materials[index].id === id) {
  19645. return this.materials[index];
  19646. }
  19647. }
  19648. return null;
  19649. };
  19650. /**
  19651. * get a material using its name
  19652. * @param {string} the material's name
  19653. * @return {BABYLON.Material|null} the material or null if none found.
  19654. */
  19655. Scene.prototype.getMaterialByName = function (name) {
  19656. for (var index = 0; index < this.materials.length; index++) {
  19657. if (this.materials[index].name === name) {
  19658. return this.materials[index];
  19659. }
  19660. }
  19661. return null;
  19662. };
  19663. Scene.prototype.getLensFlareSystemByName = function (name) {
  19664. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19665. if (this.lensFlareSystems[index].name === name) {
  19666. return this.lensFlareSystems[index];
  19667. }
  19668. }
  19669. return null;
  19670. };
  19671. Scene.prototype.getLensFlareSystemByID = function (id) {
  19672. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19673. if (this.lensFlareSystems[index].id === id) {
  19674. return this.lensFlareSystems[index];
  19675. }
  19676. }
  19677. return null;
  19678. };
  19679. Scene.prototype.getCameraByID = function (id) {
  19680. for (var index = 0; index < this.cameras.length; index++) {
  19681. if (this.cameras[index].id === id) {
  19682. return this.cameras[index];
  19683. }
  19684. }
  19685. return null;
  19686. };
  19687. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  19688. for (var index = 0; index < this.cameras.length; index++) {
  19689. if (this.cameras[index].uniqueId === uniqueId) {
  19690. return this.cameras[index];
  19691. }
  19692. }
  19693. return null;
  19694. };
  19695. /**
  19696. * get a camera using its name
  19697. * @param {string} the camera's name
  19698. * @return {BABYLON.Camera|null} the camera or null if none found.
  19699. */
  19700. Scene.prototype.getCameraByName = function (name) {
  19701. for (var index = 0; index < this.cameras.length; index++) {
  19702. if (this.cameras[index].name === name) {
  19703. return this.cameras[index];
  19704. }
  19705. }
  19706. return null;
  19707. };
  19708. /**
  19709. * get a bone using its id
  19710. * @param {string} the bone's id
  19711. * @return {BABYLON.Bone|null} the bone or null if not found
  19712. */
  19713. Scene.prototype.getBoneByID = function (id) {
  19714. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  19715. var skeleton = this.skeletons[skeletonIndex];
  19716. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  19717. if (skeleton.bones[boneIndex].id === id) {
  19718. return skeleton.bones[boneIndex];
  19719. }
  19720. }
  19721. }
  19722. return null;
  19723. };
  19724. /**
  19725. * get a bone using its id
  19726. * @param {string} the bone's name
  19727. * @return {BABYLON.Bone|null} the bone or null if not found
  19728. */
  19729. Scene.prototype.getBoneByName = function (name) {
  19730. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  19731. var skeleton = this.skeletons[skeletonIndex];
  19732. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  19733. if (skeleton.bones[boneIndex].name === name) {
  19734. return skeleton.bones[boneIndex];
  19735. }
  19736. }
  19737. }
  19738. return null;
  19739. };
  19740. /**
  19741. * get a light node using its name
  19742. * @param {string} the light's name
  19743. * @return {BABYLON.Light|null} the light or null if none found.
  19744. */
  19745. Scene.prototype.getLightByName = function (name) {
  19746. for (var index = 0; index < this.lights.length; index++) {
  19747. if (this.lights[index].name === name) {
  19748. return this.lights[index];
  19749. }
  19750. }
  19751. return null;
  19752. };
  19753. /**
  19754. * get a light node using its ID
  19755. * @param {string} the light's id
  19756. * @return {BABYLON.Light|null} the light or null if none found.
  19757. */
  19758. Scene.prototype.getLightByID = function (id) {
  19759. for (var index = 0; index < this.lights.length; index++) {
  19760. if (this.lights[index].id === id) {
  19761. return this.lights[index];
  19762. }
  19763. }
  19764. return null;
  19765. };
  19766. /**
  19767. * get a light node using its scene-generated unique ID
  19768. * @param {number} the light's unique id
  19769. * @return {BABYLON.Light|null} the light or null if none found.
  19770. */
  19771. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  19772. for (var index = 0; index < this.lights.length; index++) {
  19773. if (this.lights[index].uniqueId === uniqueId) {
  19774. return this.lights[index];
  19775. }
  19776. }
  19777. return null;
  19778. };
  19779. /**
  19780. * get a particle system by id
  19781. * @param id {number} the particle system id
  19782. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  19783. */
  19784. Scene.prototype.getParticleSystemByID = function (id) {
  19785. for (var index = 0; index < this.particleSystems.length; index++) {
  19786. if (this.particleSystems[index].id === id) {
  19787. return this.particleSystems[index];
  19788. }
  19789. }
  19790. return null;
  19791. };
  19792. /**
  19793. * get a geometry using its ID
  19794. * @param {string} the geometry's id
  19795. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  19796. */
  19797. Scene.prototype.getGeometryByID = function (id) {
  19798. for (var index = 0; index < this._geometries.length; index++) {
  19799. if (this._geometries[index].id === id) {
  19800. return this._geometries[index];
  19801. }
  19802. }
  19803. return null;
  19804. };
  19805. /**
  19806. * add a new geometry to this scene.
  19807. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  19808. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  19809. * @return {boolean} was the geometry added or not
  19810. */
  19811. Scene.prototype.pushGeometry = function (geometry, force) {
  19812. if (!force && this.getGeometryByID(geometry.id)) {
  19813. return false;
  19814. }
  19815. this._geometries.push(geometry);
  19816. //notify the collision coordinator
  19817. if (this.collisionCoordinator) {
  19818. this.collisionCoordinator.onGeometryAdded(geometry);
  19819. }
  19820. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  19821. return true;
  19822. };
  19823. /**
  19824. * Removes an existing geometry
  19825. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  19826. * @return {boolean} was the geometry removed or not
  19827. */
  19828. Scene.prototype.removeGeometry = function (geometry) {
  19829. var index = this._geometries.indexOf(geometry);
  19830. if (index > -1) {
  19831. this._geometries.splice(index, 1);
  19832. //notify the collision coordinator
  19833. if (this.collisionCoordinator) {
  19834. this.collisionCoordinator.onGeometryDeleted(geometry);
  19835. }
  19836. this.onGeometryRemovedObservable.notifyObservers(geometry);
  19837. return true;
  19838. }
  19839. return false;
  19840. };
  19841. Scene.prototype.getGeometries = function () {
  19842. return this._geometries;
  19843. };
  19844. /**
  19845. * Get the first added mesh found of a given ID
  19846. * @param {string} id - the id to search for
  19847. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19848. */
  19849. Scene.prototype.getMeshByID = function (id) {
  19850. for (var index = 0; index < this.meshes.length; index++) {
  19851. if (this.meshes[index].id === id) {
  19852. return this.meshes[index];
  19853. }
  19854. }
  19855. return null;
  19856. };
  19857. Scene.prototype.getMeshesByID = function (id) {
  19858. return this.meshes.filter(function (m) {
  19859. return m.id === id;
  19860. });
  19861. };
  19862. /**
  19863. * Get the first added transform node found of a given ID
  19864. * @param {string} id - the id to search for
  19865. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  19866. */
  19867. Scene.prototype.getTransformNodeByID = function (id) {
  19868. for (var index = 0; index < this.transformNodes.length; index++) {
  19869. if (this.transformNodes[index].id === id) {
  19870. return this.transformNodes[index];
  19871. }
  19872. }
  19873. return null;
  19874. };
  19875. Scene.prototype.getTransformNodesByID = function (id) {
  19876. return this.transformNodes.filter(function (m) {
  19877. return m.id === id;
  19878. });
  19879. };
  19880. /**
  19881. * Get a mesh with its auto-generated unique id
  19882. * @param {number} uniqueId - the unique id to search for
  19883. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19884. */
  19885. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  19886. for (var index = 0; index < this.meshes.length; index++) {
  19887. if (this.meshes[index].uniqueId === uniqueId) {
  19888. return this.meshes[index];
  19889. }
  19890. }
  19891. return null;
  19892. };
  19893. /**
  19894. * Get a the last added mesh found of a given ID
  19895. * @param {string} id - the id to search for
  19896. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19897. */
  19898. Scene.prototype.getLastMeshByID = function (id) {
  19899. for (var index = this.meshes.length - 1; index >= 0; index--) {
  19900. if (this.meshes[index].id === id) {
  19901. return this.meshes[index];
  19902. }
  19903. }
  19904. return null;
  19905. };
  19906. /**
  19907. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  19908. * @param {string} id - the id to search for
  19909. * @return {BABYLON.Node|null} the node found or null if not found at all.
  19910. */
  19911. Scene.prototype.getLastEntryByID = function (id) {
  19912. var index;
  19913. for (index = this.meshes.length - 1; index >= 0; index--) {
  19914. if (this.meshes[index].id === id) {
  19915. return this.meshes[index];
  19916. }
  19917. }
  19918. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  19919. if (this.transformNodes[index].id === id) {
  19920. return this.transformNodes[index];
  19921. }
  19922. }
  19923. for (index = this.cameras.length - 1; index >= 0; index--) {
  19924. if (this.cameras[index].id === id) {
  19925. return this.cameras[index];
  19926. }
  19927. }
  19928. for (index = this.lights.length - 1; index >= 0; index--) {
  19929. if (this.lights[index].id === id) {
  19930. return this.lights[index];
  19931. }
  19932. }
  19933. return null;
  19934. };
  19935. Scene.prototype.getNodeByID = function (id) {
  19936. var mesh = this.getMeshByID(id);
  19937. if (mesh) {
  19938. return mesh;
  19939. }
  19940. var light = this.getLightByID(id);
  19941. if (light) {
  19942. return light;
  19943. }
  19944. var camera = this.getCameraByID(id);
  19945. if (camera) {
  19946. return camera;
  19947. }
  19948. var bone = this.getBoneByID(id);
  19949. return bone;
  19950. };
  19951. Scene.prototype.getNodeByName = function (name) {
  19952. var mesh = this.getMeshByName(name);
  19953. if (mesh) {
  19954. return mesh;
  19955. }
  19956. var light = this.getLightByName(name);
  19957. if (light) {
  19958. return light;
  19959. }
  19960. var camera = this.getCameraByName(name);
  19961. if (camera) {
  19962. return camera;
  19963. }
  19964. var bone = this.getBoneByName(name);
  19965. return bone;
  19966. };
  19967. Scene.prototype.getMeshByName = function (name) {
  19968. for (var index = 0; index < this.meshes.length; index++) {
  19969. if (this.meshes[index].name === name) {
  19970. return this.meshes[index];
  19971. }
  19972. }
  19973. return null;
  19974. };
  19975. Scene.prototype.getTransformNodeByName = function (name) {
  19976. for (var index = 0; index < this.transformNodes.length; index++) {
  19977. if (this.transformNodes[index].name === name) {
  19978. return this.transformNodes[index];
  19979. }
  19980. }
  19981. return null;
  19982. };
  19983. Scene.prototype.getSoundByName = function (name) {
  19984. var index;
  19985. if (BABYLON.AudioEngine) {
  19986. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  19987. if (this.mainSoundTrack.soundCollection[index].name === name) {
  19988. return this.mainSoundTrack.soundCollection[index];
  19989. }
  19990. }
  19991. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  19992. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  19993. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  19994. return this.soundTracks[sdIndex].soundCollection[index];
  19995. }
  19996. }
  19997. }
  19998. }
  19999. return null;
  20000. };
  20001. Scene.prototype.getLastSkeletonByID = function (id) {
  20002. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  20003. if (this.skeletons[index].id === id) {
  20004. return this.skeletons[index];
  20005. }
  20006. }
  20007. return null;
  20008. };
  20009. Scene.prototype.getSkeletonById = function (id) {
  20010. for (var index = 0; index < this.skeletons.length; index++) {
  20011. if (this.skeletons[index].id === id) {
  20012. return this.skeletons[index];
  20013. }
  20014. }
  20015. return null;
  20016. };
  20017. Scene.prototype.getSkeletonByName = function (name) {
  20018. for (var index = 0; index < this.skeletons.length; index++) {
  20019. if (this.skeletons[index].name === name) {
  20020. return this.skeletons[index];
  20021. }
  20022. }
  20023. return null;
  20024. };
  20025. Scene.prototype.getMorphTargetManagerById = function (id) {
  20026. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  20027. if (this.morphTargetManagers[index].uniqueId === id) {
  20028. return this.morphTargetManagers[index];
  20029. }
  20030. }
  20031. return null;
  20032. };
  20033. Scene.prototype.isActiveMesh = function (mesh) {
  20034. return (this._activeMeshes.indexOf(mesh) !== -1);
  20035. };
  20036. /**
  20037. * Return a the first highlight layer of the scene with a given name.
  20038. * @param name The name of the highlight layer to look for.
  20039. * @return The highlight layer if found otherwise null.
  20040. */
  20041. Scene.prototype.getHighlightLayerByName = function (name) {
  20042. for (var index = 0; index < this.highlightLayers.length; index++) {
  20043. if (this.highlightLayers[index].name === name) {
  20044. return this.highlightLayers[index];
  20045. }
  20046. }
  20047. return null;
  20048. };
  20049. Object.defineProperty(Scene.prototype, "uid", {
  20050. /**
  20051. * Return a unique id as a string which can serve as an identifier for the scene
  20052. */
  20053. get: function () {
  20054. if (!this._uid) {
  20055. this._uid = BABYLON.Tools.RandomId();
  20056. }
  20057. return this._uid;
  20058. },
  20059. enumerable: true,
  20060. configurable: true
  20061. });
  20062. /**
  20063. * Add an externaly attached data from its key.
  20064. * This method call will fail and return false, if such key already exists.
  20065. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  20066. * @param key the unique key that identifies the data
  20067. * @param data the data object to associate to the key for this Engine instance
  20068. * @return true if no such key were already present and the data was added successfully, false otherwise
  20069. */
  20070. Scene.prototype.addExternalData = function (key, data) {
  20071. if (!this._externalData) {
  20072. this._externalData = new BABYLON.StringDictionary();
  20073. }
  20074. return this._externalData.add(key, data);
  20075. };
  20076. /**
  20077. * Get an externaly attached data from its key
  20078. * @param key the unique key that identifies the data
  20079. * @return the associated data, if present (can be null), or undefined if not present
  20080. */
  20081. Scene.prototype.getExternalData = function (key) {
  20082. if (!this._externalData) {
  20083. return null;
  20084. }
  20085. return this._externalData.get(key);
  20086. };
  20087. /**
  20088. * Get an externaly attached data from its key, create it using a factory if it's not already present
  20089. * @param key the unique key that identifies the data
  20090. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  20091. * @return the associated data, can be null if the factory returned null.
  20092. */
  20093. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  20094. if (!this._externalData) {
  20095. this._externalData = new BABYLON.StringDictionary();
  20096. }
  20097. return this._externalData.getOrAddWithFactory(key, factory);
  20098. };
  20099. /**
  20100. * Remove an externaly attached data from the Engine instance
  20101. * @param key the unique key that identifies the data
  20102. * @return true if the data was successfully removed, false if it doesn't exist
  20103. */
  20104. Scene.prototype.removeExternalData = function (key) {
  20105. return this._externalData.remove(key);
  20106. };
  20107. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  20108. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  20109. var material = subMesh.getMaterial();
  20110. if (mesh.showSubMeshesBoundingBox) {
  20111. var boundingInfo = subMesh.getBoundingInfo();
  20112. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  20113. }
  20114. if (material) {
  20115. // Render targets
  20116. if (material.getRenderTargetTextures) {
  20117. if (this._processedMaterials.indexOf(material) === -1) {
  20118. this._processedMaterials.push(material);
  20119. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  20120. }
  20121. }
  20122. // Dispatch
  20123. this._activeIndices.addCount(subMesh.indexCount, false);
  20124. this._renderingManager.dispatch(subMesh);
  20125. }
  20126. }
  20127. };
  20128. Scene.prototype._isInIntermediateRendering = function () {
  20129. return this._intermediateRendering;
  20130. };
  20131. /**
  20132. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  20133. */
  20134. Scene.prototype.freezeActiveMeshes = function () {
  20135. this._evaluateActiveMeshes();
  20136. this._activeMeshesFrozen = true;
  20137. return this;
  20138. };
  20139. /**
  20140. * Use this function to restart evaluating active meshes on every frame
  20141. */
  20142. Scene.prototype.unfreezeActiveMeshes = function () {
  20143. this._activeMeshesFrozen = false;
  20144. return this;
  20145. };
  20146. Scene.prototype._evaluateActiveMeshes = function () {
  20147. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  20148. return;
  20149. }
  20150. if (!this.activeCamera) {
  20151. return;
  20152. }
  20153. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  20154. this.activeCamera._activeMeshes.reset();
  20155. this._activeMeshes.reset();
  20156. this._renderingManager.reset();
  20157. this._processedMaterials.reset();
  20158. this._activeParticleSystems.reset();
  20159. this._activeSkeletons.reset();
  20160. this._softwareSkinnedMeshes.reset();
  20161. if (this._boundingBoxRenderer) {
  20162. this._boundingBoxRenderer.reset();
  20163. }
  20164. // Meshes
  20165. var meshes;
  20166. var len;
  20167. if (this._selectionOctree) {
  20168. var selection = this._selectionOctree.select(this._frustumPlanes);
  20169. meshes = selection.data;
  20170. len = selection.length;
  20171. }
  20172. else {
  20173. len = this.meshes.length;
  20174. meshes = this.meshes;
  20175. }
  20176. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  20177. var mesh = meshes[meshIndex];
  20178. if (mesh.isBlocked) {
  20179. continue;
  20180. }
  20181. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  20182. if (!mesh.isReady() || !mesh.isEnabled()) {
  20183. continue;
  20184. }
  20185. mesh.computeWorldMatrix();
  20186. // Intersections
  20187. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  20188. this._meshesForIntersections.pushNoDuplicate(mesh);
  20189. }
  20190. // Switch to current LOD
  20191. var meshLOD = mesh.getLOD(this.activeCamera);
  20192. if (!meshLOD) {
  20193. continue;
  20194. }
  20195. mesh._preActivate();
  20196. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  20197. this._activeMeshes.push(mesh);
  20198. this.activeCamera._activeMeshes.push(mesh);
  20199. mesh._activate(this._renderId);
  20200. if (meshLOD !== mesh) {
  20201. meshLOD._activate(this._renderId);
  20202. }
  20203. this._activeMesh(mesh, meshLOD);
  20204. }
  20205. }
  20206. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  20207. // Particle systems
  20208. if (this.particlesEnabled) {
  20209. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  20210. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  20211. var particleSystem = this.particleSystems[particleIndex];
  20212. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  20213. continue;
  20214. }
  20215. var emitter = particleSystem.emitter;
  20216. if (!emitter.position || emitter.isEnabled()) {
  20217. this._activeParticleSystems.push(particleSystem);
  20218. particleSystem.animate();
  20219. this._renderingManager.dispatchParticles(particleSystem);
  20220. }
  20221. }
  20222. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  20223. }
  20224. };
  20225. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  20226. if (mesh.skeleton && this.skeletonsEnabled) {
  20227. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  20228. mesh.skeleton.prepare();
  20229. }
  20230. if (!mesh.computeBonesUsingShaders) {
  20231. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  20232. }
  20233. }
  20234. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  20235. var boundingInfo = sourceMesh.getBoundingInfo();
  20236. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  20237. }
  20238. if (mesh && mesh.subMeshes) {
  20239. // Submeshes Octrees
  20240. var len;
  20241. var subMeshes;
  20242. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  20243. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  20244. len = intersections.length;
  20245. subMeshes = intersections.data;
  20246. }
  20247. else {
  20248. subMeshes = mesh.subMeshes;
  20249. len = subMeshes.length;
  20250. }
  20251. for (var subIndex = 0; subIndex < len; subIndex++) {
  20252. var subMesh = subMeshes[subIndex];
  20253. this._evaluateSubMesh(subMesh, mesh);
  20254. }
  20255. }
  20256. };
  20257. Scene.prototype.updateTransformMatrix = function (force) {
  20258. if (!this.activeCamera) {
  20259. return;
  20260. }
  20261. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  20262. };
  20263. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  20264. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  20265. };
  20266. Scene.prototype._renderForCamera = function (camera) {
  20267. if (camera && camera._skipRendering) {
  20268. return;
  20269. }
  20270. var engine = this._engine;
  20271. this.activeCamera = camera;
  20272. if (!this.activeCamera)
  20273. throw new Error("Active camera not set");
  20274. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  20275. // Viewport
  20276. engine.setViewport(this.activeCamera.viewport);
  20277. // Camera
  20278. this.resetCachedMaterial();
  20279. this._renderId++;
  20280. this.activeCamera.update();
  20281. this.updateTransformMatrix();
  20282. if (camera._alternateCamera) {
  20283. this.updateAlternateTransformMatrix(camera._alternateCamera);
  20284. this._alternateRendering = true;
  20285. }
  20286. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  20287. // Meshes
  20288. this._evaluateActiveMeshes();
  20289. // Software skinning
  20290. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  20291. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  20292. mesh.applySkeleton(mesh.skeleton);
  20293. }
  20294. // Render targets
  20295. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  20296. var needsRestoreFrameBuffer = false;
  20297. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  20298. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  20299. }
  20300. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  20301. this._intermediateRendering = true;
  20302. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  20303. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  20304. var renderTarget = this._renderTargets.data[renderIndex];
  20305. if (renderTarget._shouldRender()) {
  20306. this._renderId++;
  20307. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  20308. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  20309. }
  20310. }
  20311. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  20312. this._intermediateRendering = false;
  20313. this._renderId++;
  20314. needsRestoreFrameBuffer = true; // Restore back buffer
  20315. }
  20316. // Render HighlightLayer Texture
  20317. var stencilState = this._engine.getStencilBuffer();
  20318. var renderhighlights = false;
  20319. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  20320. this._intermediateRendering = true;
  20321. for (var i = 0; i < this.highlightLayers.length; i++) {
  20322. var highlightLayer = this.highlightLayers[i];
  20323. if (highlightLayer.shouldRender() &&
  20324. (!highlightLayer.camera ||
  20325. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  20326. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  20327. renderhighlights = true;
  20328. var renderTarget = highlightLayer._mainTexture;
  20329. if (renderTarget._shouldRender()) {
  20330. this._renderId++;
  20331. renderTarget.render(false, false);
  20332. needsRestoreFrameBuffer = true;
  20333. }
  20334. }
  20335. }
  20336. this._intermediateRendering = false;
  20337. this._renderId++;
  20338. }
  20339. if (needsRestoreFrameBuffer) {
  20340. engine.restoreDefaultFramebuffer(); // Restore back buffer
  20341. }
  20342. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  20343. // Prepare Frame
  20344. this.postProcessManager._prepareFrame();
  20345. // Backgrounds
  20346. var layerIndex;
  20347. var layer;
  20348. if (this.layers.length) {
  20349. engine.setDepthBuffer(false);
  20350. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  20351. layer = this.layers[layerIndex];
  20352. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  20353. layer.render();
  20354. }
  20355. }
  20356. engine.setDepthBuffer(true);
  20357. }
  20358. // Activate HighlightLayer stencil
  20359. if (renderhighlights) {
  20360. this._engine.setStencilBuffer(true);
  20361. }
  20362. // Render
  20363. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  20364. this._renderingManager.render(null, null, true, true);
  20365. this.onAfterDrawPhaseObservable.notifyObservers(this);
  20366. // Restore HighlightLayer stencil
  20367. if (renderhighlights) {
  20368. this._engine.setStencilBuffer(stencilState);
  20369. }
  20370. // Bounding boxes
  20371. if (this._boundingBoxRenderer) {
  20372. this._boundingBoxRenderer.render();
  20373. }
  20374. // Lens flares
  20375. if (this.lensFlaresEnabled) {
  20376. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  20377. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  20378. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  20379. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  20380. lensFlareSystem.render();
  20381. }
  20382. }
  20383. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  20384. }
  20385. // Foregrounds
  20386. if (this.layers.length) {
  20387. engine.setDepthBuffer(false);
  20388. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  20389. layer = this.layers[layerIndex];
  20390. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  20391. layer.render();
  20392. }
  20393. }
  20394. engine.setDepthBuffer(true);
  20395. }
  20396. // Highlight Layer
  20397. if (renderhighlights) {
  20398. engine.setDepthBuffer(false);
  20399. for (var i = 0; i < this.highlightLayers.length; i++) {
  20400. if (this.highlightLayers[i].shouldRender()) {
  20401. this.highlightLayers[i].render();
  20402. }
  20403. }
  20404. engine.setDepthBuffer(true);
  20405. }
  20406. // Finalize frame
  20407. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  20408. // Reset some special arrays
  20409. this._renderTargets.reset();
  20410. this._alternateRendering = false;
  20411. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  20412. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  20413. };
  20414. Scene.prototype._processSubCameras = function (camera) {
  20415. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  20416. this._renderForCamera(camera);
  20417. return;
  20418. }
  20419. // Update camera
  20420. if (this.activeCamera) {
  20421. this.activeCamera.update();
  20422. }
  20423. // rig cameras
  20424. for (var index = 0; index < camera._rigCameras.length; index++) {
  20425. this._renderForCamera(camera._rigCameras[index]);
  20426. }
  20427. this.activeCamera = camera;
  20428. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  20429. };
  20430. Scene.prototype._checkIntersections = function () {
  20431. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  20432. var sourceMesh = this._meshesForIntersections.data[index];
  20433. if (!sourceMesh.actionManager) {
  20434. continue;
  20435. }
  20436. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  20437. var action = sourceMesh.actionManager.actions[actionIndex];
  20438. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20439. var parameters = action.getTriggerParameter();
  20440. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  20441. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  20442. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  20443. if (areIntersecting && currentIntersectionInProgress === -1) {
  20444. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  20445. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  20446. sourceMesh._intersectionsInProgress.push(otherMesh);
  20447. }
  20448. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20449. sourceMesh._intersectionsInProgress.push(otherMesh);
  20450. }
  20451. }
  20452. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  20453. //They intersected, and now they don't.
  20454. //is this trigger an exit trigger? execute an event.
  20455. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20456. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  20457. }
  20458. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  20459. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20460. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  20461. }
  20462. }
  20463. }
  20464. }
  20465. }
  20466. };
  20467. Scene.prototype.render = function () {
  20468. if (this.isDisposed) {
  20469. return;
  20470. }
  20471. this._activeParticles.fetchNewFrame();
  20472. this._totalVertices.fetchNewFrame();
  20473. this._activeIndices.fetchNewFrame();
  20474. this._activeBones.fetchNewFrame();
  20475. this._meshesForIntersections.reset();
  20476. this.resetCachedMaterial();
  20477. this.onBeforeAnimationsObservable.notifyObservers(this);
  20478. // Actions
  20479. if (this.actionManager) {
  20480. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  20481. }
  20482. //Simplification Queue
  20483. if (this.simplificationQueue && !this.simplificationQueue.running) {
  20484. this.simplificationQueue.executeNext();
  20485. }
  20486. if (this._engine.isDeterministicLockStep()) {
  20487. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  20488. var defaultFPS = (60.0 / 1000.0);
  20489. var defaultFrameTime = 1000 / 60; // frame time in MS
  20490. if (this._physicsEngine) {
  20491. defaultFrameTime = this._physicsEngine.getTimeStep() / 1000; //timestep in physics engine is in seconds
  20492. }
  20493. var stepsTaken = 0;
  20494. var maxSubSteps = this._engine.getLockstepMaxSteps();
  20495. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  20496. internalSteps = Math.min(internalSteps, maxSubSteps);
  20497. do {
  20498. this.onBeforeStepObservable.notifyObservers(this);
  20499. // Animations
  20500. this._animationRatio = defaultFrameTime * defaultFPS;
  20501. this._animate();
  20502. this.onAfterAnimationsObservable.notifyObservers(this);
  20503. // Physics
  20504. if (this._physicsEngine) {
  20505. this.onBeforePhysicsObservable.notifyObservers(this);
  20506. this._physicsEngine._step(defaultFPS);
  20507. this.onAfterPhysicsObservable.notifyObservers(this);
  20508. }
  20509. this.onAfterStepObservable.notifyObservers(this);
  20510. this._currentStepId++;
  20511. if ((internalSteps > 1) && (stepsTaken != internalSteps - 1)) {
  20512. this._evaluateActiveMeshes();
  20513. }
  20514. stepsTaken++;
  20515. deltaTime -= defaultFrameTime;
  20516. } while (deltaTime > 0 && stepsTaken < maxSubSteps);
  20517. this._timeAccumulator = deltaTime;
  20518. }
  20519. else {
  20520. // Animations
  20521. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  20522. this._animationRatio = deltaTime * (60.0 / 1000.0);
  20523. this._animate();
  20524. this.onAfterAnimationsObservable.notifyObservers(this);
  20525. // Physics
  20526. if (this._physicsEngine) {
  20527. this.onBeforePhysicsObservable.notifyObservers(this);
  20528. this._physicsEngine._step(deltaTime / 1000.0);
  20529. this.onAfterPhysicsObservable.notifyObservers(this);
  20530. }
  20531. }
  20532. // Before render
  20533. this.onBeforeRenderObservable.notifyObservers(this);
  20534. // Customs render targets
  20535. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  20536. var engine = this.getEngine();
  20537. var currentActiveCamera = this.activeCamera;
  20538. if (this.renderTargetsEnabled) {
  20539. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20540. this._intermediateRendering = true;
  20541. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  20542. var renderTarget = this.customRenderTargets[customIndex];
  20543. if (renderTarget._shouldRender()) {
  20544. this._renderId++;
  20545. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  20546. if (!this.activeCamera)
  20547. throw new Error("Active camera not set");
  20548. // Viewport
  20549. engine.setViewport(this.activeCamera.viewport);
  20550. // Camera
  20551. this.updateTransformMatrix();
  20552. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  20553. }
  20554. }
  20555. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20556. this._intermediateRendering = false;
  20557. this._renderId++;
  20558. }
  20559. // Restore back buffer
  20560. if (this.customRenderTargets.length > 0) {
  20561. engine.restoreDefaultFramebuffer();
  20562. }
  20563. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  20564. this.activeCamera = currentActiveCamera;
  20565. // Procedural textures
  20566. if (this.proceduralTexturesEnabled) {
  20567. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20568. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  20569. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  20570. if (proceduralTexture._shouldRender()) {
  20571. proceduralTexture.render();
  20572. }
  20573. }
  20574. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20575. }
  20576. // Clear
  20577. if (this.autoClearDepthAndStencil || this.autoClear) {
  20578. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  20579. }
  20580. // Shadows
  20581. if (this.shadowsEnabled) {
  20582. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  20583. var light = this.lights[lightIndex];
  20584. var shadowGenerator = light.getShadowGenerator();
  20585. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  20586. var shadowMap = (shadowGenerator.getShadowMap());
  20587. if (this.textures.indexOf(shadowMap) !== -1) {
  20588. this._renderTargets.push(shadowMap);
  20589. }
  20590. }
  20591. }
  20592. }
  20593. // Depth renderer
  20594. if (this._depthRenderer) {
  20595. this._renderTargets.push(this._depthRenderer.getDepthMap());
  20596. }
  20597. // Geometry renderer
  20598. if (this._geometryBufferRenderer) {
  20599. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  20600. }
  20601. // RenderPipeline
  20602. if (this._postProcessRenderPipelineManager) {
  20603. this._postProcessRenderPipelineManager.update();
  20604. }
  20605. // Multi-cameras?
  20606. if (this.activeCameras.length > 0) {
  20607. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  20608. if (cameraIndex > 0) {
  20609. this._engine.clear(null, false, true, true);
  20610. }
  20611. this._processSubCameras(this.activeCameras[cameraIndex]);
  20612. }
  20613. }
  20614. else {
  20615. if (!this.activeCamera) {
  20616. throw new Error("No camera defined");
  20617. }
  20618. this._processSubCameras(this.activeCamera);
  20619. }
  20620. // Intersection checks
  20621. this._checkIntersections();
  20622. // Update the audio listener attached to the camera
  20623. if (BABYLON.AudioEngine) {
  20624. this._updateAudioParameters();
  20625. }
  20626. // After render
  20627. if (this.afterRender) {
  20628. this.afterRender();
  20629. }
  20630. this.onAfterRenderObservable.notifyObservers(this);
  20631. // Cleaning
  20632. for (var index = 0; index < this._toBeDisposed.length; index++) {
  20633. var data = this._toBeDisposed.data[index];
  20634. if (data) {
  20635. data.dispose();
  20636. }
  20637. this._toBeDisposed[index] = null;
  20638. }
  20639. this._toBeDisposed.reset();
  20640. if (this.dumpNextRenderTargets) {
  20641. this.dumpNextRenderTargets = false;
  20642. }
  20643. this._activeBones.addCount(0, true);
  20644. this._activeIndices.addCount(0, true);
  20645. this._activeParticles.addCount(0, true);
  20646. };
  20647. Scene.prototype._updateAudioParameters = function () {
  20648. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  20649. return;
  20650. }
  20651. var listeningCamera;
  20652. var audioEngine = BABYLON.Engine.audioEngine;
  20653. if (this.activeCameras.length > 0) {
  20654. listeningCamera = this.activeCameras[0];
  20655. }
  20656. else {
  20657. listeningCamera = this.activeCamera;
  20658. }
  20659. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  20660. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  20661. // for VR cameras
  20662. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  20663. listeningCamera = listeningCamera.rigCameras[0];
  20664. }
  20665. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  20666. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  20667. cameraDirection.normalize();
  20668. // To avoid some errors on GearVR
  20669. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  20670. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  20671. }
  20672. var i;
  20673. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20674. var sound = this.mainSoundTrack.soundCollection[i];
  20675. if (sound.useCustomAttenuation) {
  20676. sound.updateDistanceFromListener();
  20677. }
  20678. }
  20679. for (i = 0; i < this.soundTracks.length; i++) {
  20680. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20681. sound = this.soundTracks[i].soundCollection[j];
  20682. if (sound.useCustomAttenuation) {
  20683. sound.updateDistanceFromListener();
  20684. }
  20685. }
  20686. }
  20687. }
  20688. };
  20689. Object.defineProperty(Scene.prototype, "audioEnabled", {
  20690. // Audio
  20691. get: function () {
  20692. return this._audioEnabled;
  20693. },
  20694. set: function (value) {
  20695. this._audioEnabled = value;
  20696. if (BABYLON.AudioEngine) {
  20697. if (this._audioEnabled) {
  20698. this._enableAudio();
  20699. }
  20700. else {
  20701. this._disableAudio();
  20702. }
  20703. }
  20704. },
  20705. enumerable: true,
  20706. configurable: true
  20707. });
  20708. Scene.prototype._disableAudio = function () {
  20709. var i;
  20710. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20711. this.mainSoundTrack.soundCollection[i].pause();
  20712. }
  20713. for (i = 0; i < this.soundTracks.length; i++) {
  20714. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20715. this.soundTracks[i].soundCollection[j].pause();
  20716. }
  20717. }
  20718. };
  20719. Scene.prototype._enableAudio = function () {
  20720. var i;
  20721. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20722. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  20723. this.mainSoundTrack.soundCollection[i].play();
  20724. }
  20725. }
  20726. for (i = 0; i < this.soundTracks.length; i++) {
  20727. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20728. if (this.soundTracks[i].soundCollection[j].isPaused) {
  20729. this.soundTracks[i].soundCollection[j].play();
  20730. }
  20731. }
  20732. }
  20733. };
  20734. Object.defineProperty(Scene.prototype, "headphone", {
  20735. get: function () {
  20736. return this._headphone;
  20737. },
  20738. set: function (value) {
  20739. this._headphone = value;
  20740. if (BABYLON.AudioEngine) {
  20741. if (this._headphone) {
  20742. this._switchAudioModeForHeadphones();
  20743. }
  20744. else {
  20745. this._switchAudioModeForNormalSpeakers();
  20746. }
  20747. }
  20748. },
  20749. enumerable: true,
  20750. configurable: true
  20751. });
  20752. Scene.prototype._switchAudioModeForHeadphones = function () {
  20753. this.mainSoundTrack.switchPanningModelToHRTF();
  20754. for (var i = 0; i < this.soundTracks.length; i++) {
  20755. this.soundTracks[i].switchPanningModelToHRTF();
  20756. }
  20757. };
  20758. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  20759. this.mainSoundTrack.switchPanningModelToEqualPower();
  20760. for (var i = 0; i < this.soundTracks.length; i++) {
  20761. this.soundTracks[i].switchPanningModelToEqualPower();
  20762. }
  20763. };
  20764. Scene.prototype.enableDepthRenderer = function () {
  20765. if (this._depthRenderer) {
  20766. return this._depthRenderer;
  20767. }
  20768. this._depthRenderer = new BABYLON.DepthRenderer(this);
  20769. return this._depthRenderer;
  20770. };
  20771. Scene.prototype.disableDepthRenderer = function () {
  20772. if (!this._depthRenderer) {
  20773. return;
  20774. }
  20775. this._depthRenderer.dispose();
  20776. this._depthRenderer = null;
  20777. };
  20778. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  20779. if (ratio === void 0) { ratio = 1; }
  20780. if (this._geometryBufferRenderer) {
  20781. return this._geometryBufferRenderer;
  20782. }
  20783. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  20784. if (!this._geometryBufferRenderer.isSupported) {
  20785. this._geometryBufferRenderer = null;
  20786. }
  20787. return this._geometryBufferRenderer;
  20788. };
  20789. Scene.prototype.disableGeometryBufferRenderer = function () {
  20790. if (!this._geometryBufferRenderer) {
  20791. return;
  20792. }
  20793. this._geometryBufferRenderer.dispose();
  20794. this._geometryBufferRenderer = null;
  20795. };
  20796. Scene.prototype.freezeMaterials = function () {
  20797. for (var i = 0; i < this.materials.length; i++) {
  20798. this.materials[i].freeze();
  20799. }
  20800. };
  20801. Scene.prototype.unfreezeMaterials = function () {
  20802. for (var i = 0; i < this.materials.length; i++) {
  20803. this.materials[i].unfreeze();
  20804. }
  20805. };
  20806. Scene.prototype.dispose = function () {
  20807. this.beforeRender = null;
  20808. this.afterRender = null;
  20809. this.skeletons = [];
  20810. this.morphTargetManagers = [];
  20811. this.importedMeshesFiles = new Array();
  20812. this.stopAllAnimations();
  20813. this.resetCachedMaterial();
  20814. if (this._depthRenderer) {
  20815. this._depthRenderer.dispose();
  20816. }
  20817. if (this._gamepadManager) {
  20818. this._gamepadManager.dispose();
  20819. this._gamepadManager = null;
  20820. }
  20821. // Smart arrays
  20822. if (this.activeCamera) {
  20823. this.activeCamera._activeMeshes.dispose();
  20824. this.activeCamera = null;
  20825. }
  20826. this._activeMeshes.dispose();
  20827. this._renderingManager.dispose();
  20828. this._processedMaterials.dispose();
  20829. this._activeParticleSystems.dispose();
  20830. this._activeSkeletons.dispose();
  20831. this._softwareSkinnedMeshes.dispose();
  20832. this._renderTargets.dispose();
  20833. if (this._boundingBoxRenderer) {
  20834. this._boundingBoxRenderer.dispose();
  20835. }
  20836. this._meshesForIntersections.dispose();
  20837. this._toBeDisposed.dispose();
  20838. // Debug layer
  20839. if (this._debugLayer) {
  20840. this._debugLayer.hide();
  20841. }
  20842. // Events
  20843. this.onDisposeObservable.notifyObservers(this);
  20844. this.onDisposeObservable.clear();
  20845. this.onBeforeRenderObservable.clear();
  20846. this.onAfterRenderObservable.clear();
  20847. this.OnBeforeRenderTargetsRenderObservable.clear();
  20848. this.OnAfterRenderTargetsRenderObservable.clear();
  20849. this.onAfterStepObservable.clear();
  20850. this.onBeforeStepObservable.clear();
  20851. this.onBeforeActiveMeshesEvaluationObservable.clear();
  20852. this.onAfterActiveMeshesEvaluationObservable.clear();
  20853. this.onBeforeParticlesRenderingObservable.clear();
  20854. this.onAfterParticlesRenderingObservable.clear();
  20855. this.onBeforeSpritesRenderingObservable.clear();
  20856. this.onAfterSpritesRenderingObservable.clear();
  20857. this.onBeforeDrawPhaseObservable.clear();
  20858. this.onAfterDrawPhaseObservable.clear();
  20859. this.onBeforePhysicsObservable.clear();
  20860. this.onAfterPhysicsObservable.clear();
  20861. this.onBeforeAnimationsObservable.clear();
  20862. this.onAfterAnimationsObservable.clear();
  20863. this.onDataLoadedObservable.clear();
  20864. this.detachControl();
  20865. // Release sounds & sounds tracks
  20866. if (BABYLON.AudioEngine) {
  20867. this.disposeSounds();
  20868. }
  20869. // VR Helper
  20870. if (this.VRHelper) {
  20871. this.VRHelper.dispose();
  20872. }
  20873. // Detach cameras
  20874. var canvas = this._engine.getRenderingCanvas();
  20875. if (canvas) {
  20876. var index;
  20877. for (index = 0; index < this.cameras.length; index++) {
  20878. this.cameras[index].detachControl(canvas);
  20879. }
  20880. }
  20881. // Release lights
  20882. while (this.lights.length) {
  20883. this.lights[0].dispose();
  20884. }
  20885. // Release meshes
  20886. while (this.meshes.length) {
  20887. this.meshes[0].dispose(true);
  20888. }
  20889. while (this.transformNodes.length) {
  20890. this.removeTransformNode(this.transformNodes[0]);
  20891. }
  20892. // Release cameras
  20893. while (this.cameras.length) {
  20894. this.cameras[0].dispose();
  20895. }
  20896. // Release materials
  20897. if (this.defaultMaterial) {
  20898. this.defaultMaterial.dispose();
  20899. }
  20900. while (this.multiMaterials.length) {
  20901. this.multiMaterials[0].dispose();
  20902. }
  20903. while (this.materials.length) {
  20904. this.materials[0].dispose();
  20905. }
  20906. // Release particles
  20907. while (this.particleSystems.length) {
  20908. this.particleSystems[0].dispose();
  20909. }
  20910. // Release sprites
  20911. while (this.spriteManagers.length) {
  20912. this.spriteManagers[0].dispose();
  20913. }
  20914. // Release postProcesses
  20915. while (this.postProcesses.length) {
  20916. this.postProcesses[0].dispose();
  20917. }
  20918. // Release layers
  20919. while (this.layers.length) {
  20920. this.layers[0].dispose();
  20921. }
  20922. while (this.highlightLayers.length) {
  20923. this.highlightLayers[0].dispose();
  20924. }
  20925. // Release textures
  20926. while (this.textures.length) {
  20927. this.textures[0].dispose();
  20928. }
  20929. // Release UBO
  20930. this._sceneUbo.dispose();
  20931. if (this._alternateSceneUbo) {
  20932. this._alternateSceneUbo.dispose();
  20933. }
  20934. // Post-processes
  20935. this.postProcessManager.dispose();
  20936. if (this._postProcessRenderPipelineManager) {
  20937. this._postProcessRenderPipelineManager.dispose();
  20938. }
  20939. // Physics
  20940. if (this._physicsEngine) {
  20941. this.disablePhysicsEngine();
  20942. }
  20943. // Remove from engine
  20944. index = this._engine.scenes.indexOf(this);
  20945. if (index > -1) {
  20946. this._engine.scenes.splice(index, 1);
  20947. }
  20948. this._engine.wipeCaches();
  20949. this._isDisposed = true;
  20950. };
  20951. Object.defineProperty(Scene.prototype, "isDisposed", {
  20952. get: function () {
  20953. return this._isDisposed;
  20954. },
  20955. enumerable: true,
  20956. configurable: true
  20957. });
  20958. // Release sounds & sounds tracks
  20959. Scene.prototype.disposeSounds = function () {
  20960. if (!this._mainSoundTrack) {
  20961. return;
  20962. }
  20963. this.mainSoundTrack.dispose();
  20964. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  20965. this.soundTracks[scIndex].dispose();
  20966. }
  20967. };
  20968. // Octrees
  20969. Scene.prototype.getWorldExtends = function () {
  20970. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20971. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20972. for (var index = 0; index < this.meshes.length; index++) {
  20973. var mesh = this.meshes[index];
  20974. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  20975. continue;
  20976. }
  20977. mesh.computeWorldMatrix(true);
  20978. var boundingInfo = mesh.getBoundingInfo();
  20979. var minBox = boundingInfo.boundingBox.minimumWorld;
  20980. var maxBox = boundingInfo.boundingBox.maximumWorld;
  20981. BABYLON.Tools.CheckExtends(minBox, min, max);
  20982. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20983. }
  20984. return {
  20985. min: min,
  20986. max: max
  20987. };
  20988. };
  20989. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  20990. if (maxCapacity === void 0) { maxCapacity = 64; }
  20991. if (maxDepth === void 0) { maxDepth = 2; }
  20992. if (!this._selectionOctree) {
  20993. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  20994. }
  20995. var worldExtends = this.getWorldExtends();
  20996. // Update octree
  20997. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  20998. return this._selectionOctree;
  20999. };
  21000. // Picking
  21001. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  21002. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  21003. var result = BABYLON.Ray.Zero();
  21004. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  21005. return result;
  21006. };
  21007. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  21008. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  21009. var engine = this._engine;
  21010. if (!camera) {
  21011. if (!this.activeCamera)
  21012. throw new Error("Active camera not set");
  21013. camera = this.activeCamera;
  21014. }
  21015. var cameraViewport = camera.viewport;
  21016. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21017. // Moving coordinates to local viewport world
  21018. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21019. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21020. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  21021. return this;
  21022. };
  21023. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  21024. var result = BABYLON.Ray.Zero();
  21025. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  21026. return result;
  21027. };
  21028. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  21029. if (!BABYLON.PickingInfo) {
  21030. return this;
  21031. }
  21032. var engine = this._engine;
  21033. if (!camera) {
  21034. if (!this.activeCamera)
  21035. throw new Error("Active camera not set");
  21036. camera = this.activeCamera;
  21037. }
  21038. var cameraViewport = camera.viewport;
  21039. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21040. var identity = BABYLON.Matrix.Identity();
  21041. // Moving coordinates to local viewport world
  21042. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21043. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21044. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  21045. return this;
  21046. };
  21047. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  21048. if (!BABYLON.PickingInfo) {
  21049. return null;
  21050. }
  21051. var pickingInfo = null;
  21052. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21053. var mesh = this.meshes[meshIndex];
  21054. if (predicate) {
  21055. if (!predicate(mesh)) {
  21056. continue;
  21057. }
  21058. }
  21059. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21060. continue;
  21061. }
  21062. var world = mesh.getWorldMatrix();
  21063. var ray = rayFunction(world);
  21064. var result = mesh.intersects(ray, fastCheck);
  21065. if (!result || !result.hit)
  21066. continue;
  21067. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21068. continue;
  21069. pickingInfo = result;
  21070. if (fastCheck) {
  21071. break;
  21072. }
  21073. }
  21074. return pickingInfo || new BABYLON.PickingInfo();
  21075. };
  21076. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  21077. if (!BABYLON.PickingInfo) {
  21078. return null;
  21079. }
  21080. var pickingInfos = new Array();
  21081. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21082. var mesh = this.meshes[meshIndex];
  21083. if (predicate) {
  21084. if (!predicate(mesh)) {
  21085. continue;
  21086. }
  21087. }
  21088. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21089. continue;
  21090. }
  21091. var world = mesh.getWorldMatrix();
  21092. var ray = rayFunction(world);
  21093. var result = mesh.intersects(ray, false);
  21094. if (!result || !result.hit)
  21095. continue;
  21096. pickingInfos.push(result);
  21097. }
  21098. return pickingInfos;
  21099. };
  21100. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  21101. if (!BABYLON.PickingInfo) {
  21102. return null;
  21103. }
  21104. var pickingInfo = null;
  21105. if (!camera) {
  21106. if (!this.activeCamera) {
  21107. return null;
  21108. }
  21109. camera = this.activeCamera;
  21110. }
  21111. if (this.spriteManagers.length > 0) {
  21112. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  21113. var spriteManager = this.spriteManagers[spriteIndex];
  21114. if (!spriteManager.isPickable) {
  21115. continue;
  21116. }
  21117. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  21118. if (!result || !result.hit)
  21119. continue;
  21120. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21121. continue;
  21122. pickingInfo = result;
  21123. if (fastCheck) {
  21124. break;
  21125. }
  21126. }
  21127. }
  21128. return pickingInfo || new BABYLON.PickingInfo();
  21129. };
  21130. /** Launch a ray to try to pick a mesh in the scene
  21131. * @param x position on screen
  21132. * @param y position on screen
  21133. * @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
  21134. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21135. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21136. */
  21137. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  21138. var _this = this;
  21139. if (!this._tempPickingRay) {
  21140. this._tempPickingRay = BABYLON.Ray.Zero();
  21141. }
  21142. return this._internalPick(function (world) {
  21143. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  21144. return _this._tempPickingRay;
  21145. }, predicate, fastCheck);
  21146. };
  21147. /** Launch a ray to try to pick a sprite in the scene
  21148. * @param x position on screen
  21149. * @param y position on screen
  21150. * @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
  21151. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21152. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21153. */
  21154. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  21155. if (!this._tempPickingRay) {
  21156. this._tempPickingRay = BABYLON.Ray.Zero();
  21157. }
  21158. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  21159. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  21160. };
  21161. /** Use the given ray to pick a mesh in the scene
  21162. * @param ray The ray to use to pick meshes
  21163. * @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
  21164. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21165. */
  21166. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  21167. var _this = this;
  21168. return this._internalPick(function (world) {
  21169. if (!_this._pickWithRayInverseMatrix) {
  21170. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  21171. }
  21172. world.invertToRef(_this._pickWithRayInverseMatrix);
  21173. if (!_this._cachedRayForTransform) {
  21174. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  21175. }
  21176. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  21177. return _this._cachedRayForTransform;
  21178. }, predicate, fastCheck);
  21179. };
  21180. /**
  21181. * Launch a ray to try to pick a mesh in the scene
  21182. * @param x X position on screen
  21183. * @param y Y position on screen
  21184. * @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
  21185. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21186. */
  21187. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  21188. var _this = this;
  21189. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  21190. };
  21191. /**
  21192. * Launch a ray to try to pick a mesh in the scene
  21193. * @param ray Ray to use
  21194. * @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
  21195. */
  21196. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  21197. var _this = this;
  21198. return this._internalMultiPick(function (world) {
  21199. if (!_this._pickWithRayInverseMatrix) {
  21200. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  21201. }
  21202. world.invertToRef(_this._pickWithRayInverseMatrix);
  21203. if (!_this._cachedRayForTransform) {
  21204. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  21205. }
  21206. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  21207. return _this._cachedRayForTransform;
  21208. }, predicate);
  21209. };
  21210. Scene.prototype.setPointerOverMesh = function (mesh) {
  21211. if (this._pointerOverMesh === mesh) {
  21212. return;
  21213. }
  21214. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  21215. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  21216. }
  21217. this._pointerOverMesh = mesh;
  21218. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  21219. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  21220. }
  21221. };
  21222. Scene.prototype.getPointerOverMesh = function () {
  21223. return this._pointerOverMesh;
  21224. };
  21225. Scene.prototype.setPointerOverSprite = function (sprite) {
  21226. if (this._pointerOverSprite === sprite) {
  21227. return;
  21228. }
  21229. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  21230. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  21231. }
  21232. this._pointerOverSprite = sprite;
  21233. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  21234. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  21235. }
  21236. };
  21237. Scene.prototype.getPointerOverSprite = function () {
  21238. return this._pointerOverSprite;
  21239. };
  21240. // Physics
  21241. Scene.prototype.getPhysicsEngine = function () {
  21242. return this._physicsEngine;
  21243. };
  21244. /**
  21245. * Enables physics to the current scene
  21246. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  21247. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  21248. * @return {boolean} was the physics engine initialized
  21249. */
  21250. Scene.prototype.enablePhysics = function (gravity, plugin) {
  21251. if (gravity === void 0) { gravity = null; }
  21252. if (this._physicsEngine) {
  21253. return true;
  21254. }
  21255. try {
  21256. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  21257. return true;
  21258. }
  21259. catch (e) {
  21260. BABYLON.Tools.Error(e.message);
  21261. return false;
  21262. }
  21263. };
  21264. Scene.prototype.disablePhysicsEngine = function () {
  21265. if (!this._physicsEngine) {
  21266. return;
  21267. }
  21268. this._physicsEngine.dispose();
  21269. this._physicsEngine = null;
  21270. };
  21271. Scene.prototype.isPhysicsEnabled = function () {
  21272. return this._physicsEngine !== undefined;
  21273. };
  21274. Scene.prototype.deleteCompoundImpostor = function (compound) {
  21275. var mesh = compound.parts[0].mesh;
  21276. if (mesh.physicsImpostor) {
  21277. mesh.physicsImpostor.dispose();
  21278. mesh.physicsImpostor = null;
  21279. }
  21280. };
  21281. // Misc.
  21282. Scene.prototype._rebuildGeometries = function () {
  21283. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  21284. var geometry = _a[_i];
  21285. geometry._rebuild();
  21286. }
  21287. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  21288. var mesh = _c[_b];
  21289. mesh._rebuild();
  21290. }
  21291. if (this.postProcessManager) {
  21292. this.postProcessManager._rebuild();
  21293. }
  21294. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  21295. var layer = _e[_d];
  21296. layer._rebuild();
  21297. }
  21298. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  21299. var highlightLayer = _g[_f];
  21300. highlightLayer._rebuild();
  21301. }
  21302. if (this._boundingBoxRenderer) {
  21303. this._boundingBoxRenderer._rebuild();
  21304. }
  21305. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  21306. var system = _j[_h];
  21307. system.rebuild();
  21308. }
  21309. if (this._postProcessRenderPipelineManager) {
  21310. this._postProcessRenderPipelineManager._rebuild();
  21311. }
  21312. };
  21313. Scene.prototype._rebuildTextures = function () {
  21314. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  21315. var texture = _a[_i];
  21316. texture._rebuild();
  21317. }
  21318. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21319. };
  21320. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  21321. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  21322. if (replace === void 0) { replace = false; }
  21323. if (attachCameraControls === void 0) { attachCameraControls = false; }
  21324. // Dispose existing camera or light in replace mode.
  21325. if (replace) {
  21326. if (this.activeCamera) {
  21327. this.activeCamera.dispose();
  21328. this.activeCamera = null;
  21329. }
  21330. if (this.lights) {
  21331. for (var i = 0; i < this.lights.length; i++) {
  21332. this.lights[i].dispose();
  21333. }
  21334. }
  21335. }
  21336. // Light
  21337. if (this.lights.length === 0) {
  21338. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  21339. }
  21340. // Camera
  21341. if (!this.activeCamera) {
  21342. var worldExtends = this.getWorldExtends();
  21343. var worldSize = worldExtends.max.subtract(worldExtends.min);
  21344. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  21345. var camera;
  21346. var radius = worldSize.length() * 1.5;
  21347. if (createArcRotateCamera) {
  21348. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  21349. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  21350. arcRotateCamera.wheelPrecision = 100 / radius;
  21351. camera = arcRotateCamera;
  21352. }
  21353. else {
  21354. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  21355. freeCamera.setTarget(worldCenter);
  21356. camera = freeCamera;
  21357. }
  21358. camera.minZ = radius * 0.01;
  21359. camera.maxZ = radius * 100;
  21360. camera.speed = radius * 0.2;
  21361. this.activeCamera = camera;
  21362. var canvas = this.getEngine().getRenderingCanvas();
  21363. if (attachCameraControls && canvas) {
  21364. camera.attachControl(canvas);
  21365. }
  21366. }
  21367. };
  21368. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  21369. if (pbr === void 0) { pbr = false; }
  21370. if (scale === void 0) { scale = 1000; }
  21371. if (blur === void 0) { blur = 0; }
  21372. if (environmentTexture) {
  21373. this.environmentTexture = environmentTexture;
  21374. }
  21375. if (!this.environmentTexture) {
  21376. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  21377. return null;
  21378. }
  21379. // Skybox
  21380. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  21381. if (pbr) {
  21382. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  21383. hdrSkyboxMaterial.backFaceCulling = false;
  21384. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  21385. if (hdrSkyboxMaterial.reflectionTexture) {
  21386. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  21387. }
  21388. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  21389. hdrSkyboxMaterial.disableLighting = true;
  21390. hdrSkyboxMaterial.twoSidedLighting = true;
  21391. hdrSkybox.infiniteDistance = true;
  21392. hdrSkybox.material = hdrSkyboxMaterial;
  21393. }
  21394. else {
  21395. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  21396. skyboxMaterial.backFaceCulling = false;
  21397. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  21398. if (skyboxMaterial.reflectionTexture) {
  21399. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  21400. }
  21401. skyboxMaterial.disableLighting = true;
  21402. hdrSkybox.infiniteDistance = true;
  21403. hdrSkybox.material = skyboxMaterial;
  21404. }
  21405. return hdrSkybox;
  21406. };
  21407. Scene.prototype.createDefaultEnvironment = function (options) {
  21408. if (BABYLON.EnvironmentHelper) {
  21409. return new BABYLON.EnvironmentHelper(options, this);
  21410. }
  21411. return null;
  21412. };
  21413. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  21414. if (webVROptions === void 0) { webVROptions = {}; }
  21415. return new BABYLON.VRExperienceHelper(this, webVROptions);
  21416. };
  21417. // Tags
  21418. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  21419. if (tagsQuery === undefined) {
  21420. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  21421. return list;
  21422. }
  21423. var listByTags = [];
  21424. forEach = forEach || (function (item) { return; });
  21425. for (var i in list) {
  21426. var item = list[i];
  21427. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  21428. listByTags.push(item);
  21429. forEach(item);
  21430. }
  21431. }
  21432. return listByTags;
  21433. };
  21434. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  21435. return this._getByTags(this.meshes, tagsQuery, forEach);
  21436. };
  21437. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  21438. return this._getByTags(this.cameras, tagsQuery, forEach);
  21439. };
  21440. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  21441. return this._getByTags(this.lights, tagsQuery, forEach);
  21442. };
  21443. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  21444. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  21445. };
  21446. /**
  21447. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21448. * This allowed control for front to back rendering or reversly depending of the special needs.
  21449. *
  21450. * @param renderingGroupId The rendering group id corresponding to its index
  21451. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21452. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21453. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21454. */
  21455. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21456. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21457. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21458. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21459. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  21460. };
  21461. /**
  21462. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21463. *
  21464. * @param renderingGroupId The rendering group id corresponding to its index
  21465. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21466. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21467. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21468. */
  21469. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21470. if (depth === void 0) { depth = true; }
  21471. if (stencil === void 0) { stencil = true; }
  21472. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  21473. };
  21474. /**
  21475. * Will flag all materials as dirty to trigger new shader compilation
  21476. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  21477. */
  21478. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  21479. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  21480. var material = _a[_i];
  21481. if (predicate && !predicate(material)) {
  21482. continue;
  21483. }
  21484. material.markAsDirty(flag);
  21485. }
  21486. };
  21487. // Statics
  21488. Scene._FOGMODE_NONE = 0;
  21489. Scene._FOGMODE_EXP = 1;
  21490. Scene._FOGMODE_EXP2 = 2;
  21491. Scene._FOGMODE_LINEAR = 3;
  21492. Scene._uniqueIdCounter = 0;
  21493. Scene.MinDeltaTime = 1.0;
  21494. Scene.MaxDeltaTime = 1000.0;
  21495. /** The distance in pixel that you have to move to prevent some events */
  21496. Scene.DragMovementThreshold = 10; // in pixels
  21497. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  21498. Scene.LongPressDelay = 500; // in milliseconds
  21499. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  21500. Scene.DoubleClickDelay = 300; // in milliseconds
  21501. /** If you need to check double click without raising a single click at first click, enable this flag */
  21502. Scene.ExclusiveDoubleClickMode = false;
  21503. return Scene;
  21504. }());
  21505. BABYLON.Scene = Scene;
  21506. })(BABYLON || (BABYLON = {}));
  21507. //# sourceMappingURL=babylon.scene.js.map
  21508. var BABYLON;
  21509. (function (BABYLON) {
  21510. var Buffer = /** @class */ (function () {
  21511. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  21512. if (instanced === void 0) { instanced = false; }
  21513. if (engine instanceof BABYLON.Mesh) {
  21514. this._engine = engine.getScene().getEngine();
  21515. }
  21516. else {
  21517. this._engine = engine;
  21518. }
  21519. this._updatable = updatable;
  21520. this._data = data;
  21521. this._strideSize = stride;
  21522. if (!postponeInternalCreation) {
  21523. this.create();
  21524. }
  21525. this._instanced = instanced;
  21526. this._instanceDivisor = instanced ? 1 : 0;
  21527. }
  21528. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  21529. // a lot of these parameters are ignored as they are overriden by the buffer
  21530. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  21531. };
  21532. // Properties
  21533. Buffer.prototype.isUpdatable = function () {
  21534. return this._updatable;
  21535. };
  21536. Buffer.prototype.getData = function () {
  21537. return this._data;
  21538. };
  21539. Buffer.prototype.getBuffer = function () {
  21540. return this._buffer;
  21541. };
  21542. Buffer.prototype.getStrideSize = function () {
  21543. return this._strideSize;
  21544. };
  21545. Buffer.prototype.getIsInstanced = function () {
  21546. return this._instanced;
  21547. };
  21548. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  21549. get: function () {
  21550. return this._instanceDivisor;
  21551. },
  21552. set: function (value) {
  21553. this._instanceDivisor = value;
  21554. if (value == 0) {
  21555. this._instanced = false;
  21556. }
  21557. else {
  21558. this._instanced = true;
  21559. }
  21560. },
  21561. enumerable: true,
  21562. configurable: true
  21563. });
  21564. // Methods
  21565. Buffer.prototype.create = function (data) {
  21566. if (data === void 0) { data = null; }
  21567. if (!data && this._buffer) {
  21568. return; // nothing to do
  21569. }
  21570. data = data || this._data;
  21571. if (!data) {
  21572. return;
  21573. }
  21574. if (!this._buffer) {
  21575. if (this._updatable) {
  21576. this._buffer = this._engine.createDynamicVertexBuffer(data);
  21577. this._data = data;
  21578. }
  21579. else {
  21580. this._buffer = this._engine.createVertexBuffer(data);
  21581. }
  21582. }
  21583. else if (this._updatable) {
  21584. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  21585. this._data = data;
  21586. }
  21587. };
  21588. Buffer.prototype._rebuild = function () {
  21589. this._buffer = null;
  21590. this.create(this._data);
  21591. };
  21592. Buffer.prototype.update = function (data) {
  21593. this.create(data);
  21594. };
  21595. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  21596. if (!this._buffer) {
  21597. return;
  21598. }
  21599. if (this._updatable) {
  21600. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  21601. this._data = null;
  21602. }
  21603. };
  21604. Buffer.prototype.dispose = function () {
  21605. if (!this._buffer) {
  21606. return;
  21607. }
  21608. if (this._engine._releaseBuffer(this._buffer)) {
  21609. this._buffer = null;
  21610. }
  21611. };
  21612. return Buffer;
  21613. }());
  21614. BABYLON.Buffer = Buffer;
  21615. })(BABYLON || (BABYLON = {}));
  21616. //# sourceMappingURL=babylon.buffer.js.map
  21617. var BABYLON;
  21618. (function (BABYLON) {
  21619. var VertexBuffer = /** @class */ (function () {
  21620. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  21621. if (!stride) {
  21622. // Deduce stride from kind
  21623. switch (kind) {
  21624. case VertexBuffer.PositionKind:
  21625. stride = 3;
  21626. break;
  21627. case VertexBuffer.NormalKind:
  21628. stride = 3;
  21629. break;
  21630. case VertexBuffer.UVKind:
  21631. case VertexBuffer.UV2Kind:
  21632. case VertexBuffer.UV3Kind:
  21633. case VertexBuffer.UV4Kind:
  21634. case VertexBuffer.UV5Kind:
  21635. case VertexBuffer.UV6Kind:
  21636. stride = 2;
  21637. break;
  21638. case VertexBuffer.TangentKind:
  21639. case VertexBuffer.ColorKind:
  21640. stride = 4;
  21641. break;
  21642. case VertexBuffer.MatricesIndicesKind:
  21643. case VertexBuffer.MatricesIndicesExtraKind:
  21644. stride = 4;
  21645. break;
  21646. case VertexBuffer.MatricesWeightsKind:
  21647. case VertexBuffer.MatricesWeightsExtraKind:
  21648. default:
  21649. stride = 4;
  21650. break;
  21651. }
  21652. }
  21653. if (data instanceof BABYLON.Buffer) {
  21654. if (!stride) {
  21655. stride = data.getStrideSize();
  21656. }
  21657. this._buffer = data;
  21658. this._ownsBuffer = false;
  21659. }
  21660. else {
  21661. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  21662. this._ownsBuffer = true;
  21663. }
  21664. this._stride = stride;
  21665. this._offset = offset ? offset : 0;
  21666. this._size = size ? size : stride;
  21667. this._kind = kind;
  21668. }
  21669. VertexBuffer.prototype._rebuild = function () {
  21670. if (!this._buffer) {
  21671. return;
  21672. }
  21673. this._buffer._rebuild();
  21674. };
  21675. /**
  21676. * Returns the kind of the VertexBuffer (string).
  21677. */
  21678. VertexBuffer.prototype.getKind = function () {
  21679. return this._kind;
  21680. };
  21681. // Properties
  21682. /**
  21683. * Boolean : is the VertexBuffer updatable ?
  21684. */
  21685. VertexBuffer.prototype.isUpdatable = function () {
  21686. return this._buffer.isUpdatable();
  21687. };
  21688. /**
  21689. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  21690. */
  21691. VertexBuffer.prototype.getData = function () {
  21692. return this._buffer.getData();
  21693. };
  21694. /**
  21695. * Returns the WebGLBuffer associated to the VertexBuffer.
  21696. */
  21697. VertexBuffer.prototype.getBuffer = function () {
  21698. return this._buffer.getBuffer();
  21699. };
  21700. /**
  21701. * Returns the stride of the VertexBuffer (integer).
  21702. */
  21703. VertexBuffer.prototype.getStrideSize = function () {
  21704. return this._stride;
  21705. };
  21706. /**
  21707. * Returns the offset (integer).
  21708. */
  21709. VertexBuffer.prototype.getOffset = function () {
  21710. return this._offset;
  21711. };
  21712. /**
  21713. * Returns the VertexBuffer total size (integer).
  21714. */
  21715. VertexBuffer.prototype.getSize = function () {
  21716. return this._size;
  21717. };
  21718. /**
  21719. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  21720. */
  21721. VertexBuffer.prototype.getIsInstanced = function () {
  21722. return this._buffer.getIsInstanced();
  21723. };
  21724. /**
  21725. * Returns the instancing divisor, zero for non-instanced (integer).
  21726. */
  21727. VertexBuffer.prototype.getInstanceDivisor = function () {
  21728. return this._buffer.instanceDivisor;
  21729. };
  21730. // Methods
  21731. /**
  21732. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  21733. * Returns the created WebGLBuffer.
  21734. */
  21735. VertexBuffer.prototype.create = function (data) {
  21736. return this._buffer.create(data);
  21737. };
  21738. /**
  21739. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21740. * Returns the updated WebGLBuffer.
  21741. */
  21742. VertexBuffer.prototype.update = function (data) {
  21743. return this._buffer.update(data);
  21744. };
  21745. /**
  21746. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21747. * Returns the directly updated WebGLBuffer.
  21748. */
  21749. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  21750. return this._buffer.updateDirectly(data, offset);
  21751. };
  21752. /**
  21753. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  21754. */
  21755. VertexBuffer.prototype.dispose = function () {
  21756. if (this._ownsBuffer) {
  21757. this._buffer.dispose();
  21758. }
  21759. };
  21760. Object.defineProperty(VertexBuffer, "PositionKind", {
  21761. get: function () {
  21762. return VertexBuffer._PositionKind;
  21763. },
  21764. enumerable: true,
  21765. configurable: true
  21766. });
  21767. Object.defineProperty(VertexBuffer, "NormalKind", {
  21768. get: function () {
  21769. return VertexBuffer._NormalKind;
  21770. },
  21771. enumerable: true,
  21772. configurable: true
  21773. });
  21774. Object.defineProperty(VertexBuffer, "TangentKind", {
  21775. get: function () {
  21776. return VertexBuffer._TangentKind;
  21777. },
  21778. enumerable: true,
  21779. configurable: true
  21780. });
  21781. Object.defineProperty(VertexBuffer, "UVKind", {
  21782. get: function () {
  21783. return VertexBuffer._UVKind;
  21784. },
  21785. enumerable: true,
  21786. configurable: true
  21787. });
  21788. Object.defineProperty(VertexBuffer, "UV2Kind", {
  21789. get: function () {
  21790. return VertexBuffer._UV2Kind;
  21791. },
  21792. enumerable: true,
  21793. configurable: true
  21794. });
  21795. Object.defineProperty(VertexBuffer, "UV3Kind", {
  21796. get: function () {
  21797. return VertexBuffer._UV3Kind;
  21798. },
  21799. enumerable: true,
  21800. configurable: true
  21801. });
  21802. Object.defineProperty(VertexBuffer, "UV4Kind", {
  21803. get: function () {
  21804. return VertexBuffer._UV4Kind;
  21805. },
  21806. enumerable: true,
  21807. configurable: true
  21808. });
  21809. Object.defineProperty(VertexBuffer, "UV5Kind", {
  21810. get: function () {
  21811. return VertexBuffer._UV5Kind;
  21812. },
  21813. enumerable: true,
  21814. configurable: true
  21815. });
  21816. Object.defineProperty(VertexBuffer, "UV6Kind", {
  21817. get: function () {
  21818. return VertexBuffer._UV6Kind;
  21819. },
  21820. enumerable: true,
  21821. configurable: true
  21822. });
  21823. Object.defineProperty(VertexBuffer, "ColorKind", {
  21824. get: function () {
  21825. return VertexBuffer._ColorKind;
  21826. },
  21827. enumerable: true,
  21828. configurable: true
  21829. });
  21830. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  21831. get: function () {
  21832. return VertexBuffer._MatricesIndicesKind;
  21833. },
  21834. enumerable: true,
  21835. configurable: true
  21836. });
  21837. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  21838. get: function () {
  21839. return VertexBuffer._MatricesWeightsKind;
  21840. },
  21841. enumerable: true,
  21842. configurable: true
  21843. });
  21844. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  21845. get: function () {
  21846. return VertexBuffer._MatricesIndicesExtraKind;
  21847. },
  21848. enumerable: true,
  21849. configurable: true
  21850. });
  21851. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  21852. get: function () {
  21853. return VertexBuffer._MatricesWeightsExtraKind;
  21854. },
  21855. enumerable: true,
  21856. configurable: true
  21857. });
  21858. // Enums
  21859. VertexBuffer._PositionKind = "position";
  21860. VertexBuffer._NormalKind = "normal";
  21861. VertexBuffer._TangentKind = "tangent";
  21862. VertexBuffer._UVKind = "uv";
  21863. VertexBuffer._UV2Kind = "uv2";
  21864. VertexBuffer._UV3Kind = "uv3";
  21865. VertexBuffer._UV4Kind = "uv4";
  21866. VertexBuffer._UV5Kind = "uv5";
  21867. VertexBuffer._UV6Kind = "uv6";
  21868. VertexBuffer._ColorKind = "color";
  21869. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  21870. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  21871. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  21872. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  21873. return VertexBuffer;
  21874. }());
  21875. BABYLON.VertexBuffer = VertexBuffer;
  21876. })(BABYLON || (BABYLON = {}));
  21877. //# sourceMappingURL=babylon.vertexBuffer.js.map
  21878. var BABYLON;
  21879. (function (BABYLON) {
  21880. var InternalTexture = /** @class */ (function () {
  21881. function InternalTexture(engine, dataSource) {
  21882. this.onLoadedObservable = new BABYLON.Observable();
  21883. // Private
  21884. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  21885. this._references = 1;
  21886. this._engine = engine;
  21887. this._dataSource = dataSource;
  21888. this._webGLTexture = engine._createTexture();
  21889. }
  21890. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  21891. get: function () {
  21892. return this._dataSource;
  21893. },
  21894. enumerable: true,
  21895. configurable: true
  21896. });
  21897. InternalTexture.prototype.incrementReferences = function () {
  21898. this._references++;
  21899. };
  21900. InternalTexture.prototype.updateSize = function (width, height, depth) {
  21901. if (depth === void 0) { depth = 1; }
  21902. this.width = width;
  21903. this.height = height;
  21904. this.depth = depth;
  21905. this.baseWidth = width;
  21906. this.baseHeight = height;
  21907. this.baseDepth = depth;
  21908. this._size = width * height * depth;
  21909. };
  21910. InternalTexture.prototype._rebuild = function () {
  21911. var _this = this;
  21912. var proxy;
  21913. this.isReady = false;
  21914. this._cachedCoordinatesMode = null;
  21915. this._cachedWrapU = null;
  21916. this._cachedWrapV = null;
  21917. this._cachedAnisotropicFilteringLevel = null;
  21918. switch (this._dataSource) {
  21919. case InternalTexture.DATASOURCE_TEMP:
  21920. return;
  21921. case InternalTexture.DATASOURCE_URL:
  21922. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  21923. _this.isReady = true;
  21924. }, null, this._buffer, undefined, this.format);
  21925. proxy._swapAndDie(this);
  21926. return;
  21927. case InternalTexture.DATASOURCE_RAW:
  21928. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21929. proxy._swapAndDie(this);
  21930. this.isReady = true;
  21931. return;
  21932. case InternalTexture.DATASOURCE_RAW3D:
  21933. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21934. proxy._swapAndDie(this);
  21935. this.isReady = true;
  21936. return;
  21937. case InternalTexture.DATASOURCE_DYNAMIC:
  21938. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  21939. proxy._swapAndDie(this);
  21940. // The engine will make sure to update content so no need to flag it as isReady = true
  21941. return;
  21942. case InternalTexture.DATASOURCE_RENDERTARGET:
  21943. var options = new BABYLON.RenderTargetCreationOptions();
  21944. options.generateDepthBuffer = this._generateDepthBuffer;
  21945. options.generateMipMaps = this.generateMipMaps;
  21946. options.generateStencilBuffer = this._generateStencilBuffer;
  21947. options.samplingMode = this.samplingMode;
  21948. options.type = this.type;
  21949. if (this.isCube) {
  21950. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  21951. }
  21952. else {
  21953. var size = {
  21954. width: this.width,
  21955. height: this.height
  21956. };
  21957. proxy = this._engine.createRenderTargetTexture(size, options);
  21958. }
  21959. proxy._swapAndDie(this);
  21960. this.isReady = true;
  21961. return;
  21962. case InternalTexture.DATASOURCE_CUBE:
  21963. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  21964. _this.isReady = true;
  21965. }, null, this.format, this._extension);
  21966. proxy._swapAndDie(this);
  21967. return;
  21968. case InternalTexture.DATASOURCE_CUBERAW:
  21969. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21970. proxy._swapAndDie(this);
  21971. this.isReady = true;
  21972. return;
  21973. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  21974. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  21975. if (proxy) {
  21976. proxy._swapAndDie(_this);
  21977. }
  21978. _this.isReady = true;
  21979. }, null, this.format, this._extension);
  21980. return;
  21981. }
  21982. };
  21983. InternalTexture.prototype._swapAndDie = function (target) {
  21984. target._webGLTexture = this._webGLTexture;
  21985. if (this._framebuffer) {
  21986. target._framebuffer = this._framebuffer;
  21987. }
  21988. if (this._depthStencilBuffer) {
  21989. target._depthStencilBuffer = this._depthStencilBuffer;
  21990. }
  21991. if (this._lodTextureHigh) {
  21992. if (target._lodTextureHigh) {
  21993. target._lodTextureHigh.dispose();
  21994. }
  21995. target._lodTextureHigh = this._lodTextureHigh;
  21996. }
  21997. if (this._lodTextureMid) {
  21998. if (target._lodTextureMid) {
  21999. target._lodTextureMid.dispose();
  22000. }
  22001. target._lodTextureMid = this._lodTextureMid;
  22002. }
  22003. if (this._lodTextureLow) {
  22004. if (target._lodTextureLow) {
  22005. target._lodTextureLow.dispose();
  22006. }
  22007. target._lodTextureLow = this._lodTextureLow;
  22008. }
  22009. var cache = this._engine.getLoadedTexturesCache();
  22010. var index = cache.indexOf(this);
  22011. if (index !== -1) {
  22012. cache.splice(index, 1);
  22013. }
  22014. };
  22015. InternalTexture.prototype.dispose = function () {
  22016. if (!this._webGLTexture) {
  22017. return;
  22018. }
  22019. this._references--;
  22020. if (this._references === 0) {
  22021. this._engine._releaseTexture(this);
  22022. this._webGLTexture = null;
  22023. }
  22024. };
  22025. InternalTexture.DATASOURCE_UNKNOWN = 0;
  22026. InternalTexture.DATASOURCE_URL = 1;
  22027. InternalTexture.DATASOURCE_TEMP = 2;
  22028. InternalTexture.DATASOURCE_RAW = 3;
  22029. InternalTexture.DATASOURCE_DYNAMIC = 4;
  22030. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  22031. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  22032. InternalTexture.DATASOURCE_CUBE = 7;
  22033. InternalTexture.DATASOURCE_CUBERAW = 8;
  22034. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  22035. InternalTexture.DATASOURCE_RAW3D = 10;
  22036. return InternalTexture;
  22037. }());
  22038. BABYLON.InternalTexture = InternalTexture;
  22039. })(BABYLON || (BABYLON = {}));
  22040. //# sourceMappingURL=babylon.internalTexture.js.map
  22041. var BABYLON;
  22042. (function (BABYLON) {
  22043. var BaseTexture = /** @class */ (function () {
  22044. function BaseTexture(scene) {
  22045. this._hasAlpha = false;
  22046. this.getAlphaFromRGB = false;
  22047. this.level = 1;
  22048. this.coordinatesIndex = 0;
  22049. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  22050. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  22051. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  22052. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  22053. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  22054. this.isCube = false;
  22055. this.is3D = false;
  22056. this.gammaSpace = true;
  22057. this.invertZ = false;
  22058. this.lodLevelInAlpha = false;
  22059. this.lodGenerationOffset = 0.0;
  22060. this.lodGenerationScale = 0.8;
  22061. this.isRenderTarget = false;
  22062. this.animations = new Array();
  22063. /**
  22064. * An event triggered when the texture is disposed.
  22065. * @type {BABYLON.Observable}
  22066. */
  22067. this.onDisposeObservable = new BABYLON.Observable();
  22068. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22069. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  22070. if (this._scene) {
  22071. this._scene.textures.push(this);
  22072. }
  22073. this._uid = null;
  22074. }
  22075. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  22076. get: function () {
  22077. return this._hasAlpha;
  22078. },
  22079. set: function (value) {
  22080. if (this._hasAlpha === value) {
  22081. return;
  22082. }
  22083. this._hasAlpha = value;
  22084. if (this._scene) {
  22085. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22086. }
  22087. },
  22088. enumerable: true,
  22089. configurable: true
  22090. });
  22091. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  22092. get: function () {
  22093. return this._coordinatesMode;
  22094. },
  22095. set: function (value) {
  22096. if (this._coordinatesMode === value) {
  22097. return;
  22098. }
  22099. this._coordinatesMode = value;
  22100. if (this._scene) {
  22101. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22102. }
  22103. },
  22104. enumerable: true,
  22105. configurable: true
  22106. });
  22107. Object.defineProperty(BaseTexture.prototype, "uid", {
  22108. get: function () {
  22109. if (!this._uid) {
  22110. this._uid = BABYLON.Tools.RandomId();
  22111. }
  22112. return this._uid;
  22113. },
  22114. enumerable: true,
  22115. configurable: true
  22116. });
  22117. BaseTexture.prototype.toString = function () {
  22118. return this.name;
  22119. };
  22120. BaseTexture.prototype.getClassName = function () {
  22121. return "BaseTexture";
  22122. };
  22123. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  22124. set: function (callback) {
  22125. if (this._onDisposeObserver) {
  22126. this.onDisposeObservable.remove(this._onDisposeObserver);
  22127. }
  22128. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22129. },
  22130. enumerable: true,
  22131. configurable: true
  22132. });
  22133. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  22134. get: function () {
  22135. return true;
  22136. },
  22137. enumerable: true,
  22138. configurable: true
  22139. });
  22140. BaseTexture.prototype.getScene = function () {
  22141. return this._scene;
  22142. };
  22143. BaseTexture.prototype.getTextureMatrix = function () {
  22144. return BABYLON.Matrix.IdentityReadOnly;
  22145. };
  22146. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  22147. return BABYLON.Matrix.IdentityReadOnly;
  22148. };
  22149. BaseTexture.prototype.getInternalTexture = function () {
  22150. return this._texture;
  22151. };
  22152. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  22153. return !this.isBlocking || this.isReady();
  22154. };
  22155. BaseTexture.prototype.isReady = function () {
  22156. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22157. this.delayLoad();
  22158. return false;
  22159. }
  22160. if (this._texture) {
  22161. return this._texture.isReady;
  22162. }
  22163. return false;
  22164. };
  22165. BaseTexture.prototype.getSize = function () {
  22166. if (this._texture && this._texture.width) {
  22167. return new BABYLON.Size(this._texture.width, this._texture.height);
  22168. }
  22169. if (this._texture && this._texture._size) {
  22170. return new BABYLON.Size(this._texture._size, this._texture._size);
  22171. }
  22172. return BABYLON.Size.Zero();
  22173. };
  22174. BaseTexture.prototype.getBaseSize = function () {
  22175. if (!this.isReady() || !this._texture)
  22176. return BABYLON.Size.Zero();
  22177. if (this._texture._size) {
  22178. return new BABYLON.Size(this._texture._size, this._texture._size);
  22179. }
  22180. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  22181. };
  22182. BaseTexture.prototype.scale = function (ratio) {
  22183. };
  22184. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  22185. get: function () {
  22186. return false;
  22187. },
  22188. enumerable: true,
  22189. configurable: true
  22190. });
  22191. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  22192. if (!this._scene) {
  22193. return null;
  22194. }
  22195. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22196. for (var index = 0; index < texturesCache.length; index++) {
  22197. var texturesCacheEntry = texturesCache[index];
  22198. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  22199. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  22200. texturesCacheEntry.incrementReferences();
  22201. return texturesCacheEntry;
  22202. }
  22203. }
  22204. }
  22205. return null;
  22206. };
  22207. BaseTexture.prototype._rebuild = function () {
  22208. };
  22209. BaseTexture.prototype.delayLoad = function () {
  22210. };
  22211. BaseTexture.prototype.clone = function () {
  22212. return null;
  22213. };
  22214. Object.defineProperty(BaseTexture.prototype, "textureType", {
  22215. get: function () {
  22216. if (!this._texture) {
  22217. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  22218. }
  22219. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  22220. },
  22221. enumerable: true,
  22222. configurable: true
  22223. });
  22224. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  22225. get: function () {
  22226. if (!this._texture) {
  22227. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  22228. }
  22229. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  22230. },
  22231. enumerable: true,
  22232. configurable: true
  22233. });
  22234. BaseTexture.prototype.readPixels = function (faceIndex) {
  22235. if (faceIndex === void 0) { faceIndex = 0; }
  22236. if (!this._texture) {
  22237. return null;
  22238. }
  22239. var size = this.getSize();
  22240. var scene = this.getScene();
  22241. if (!scene) {
  22242. return null;
  22243. }
  22244. var engine = scene.getEngine();
  22245. if (this._texture.isCube) {
  22246. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  22247. }
  22248. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  22249. };
  22250. BaseTexture.prototype.releaseInternalTexture = function () {
  22251. if (this._texture) {
  22252. this._texture.dispose();
  22253. this._texture = null;
  22254. }
  22255. };
  22256. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  22257. get: function () {
  22258. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  22259. return null;
  22260. }
  22261. if (!this._texture._sphericalPolynomial) {
  22262. this._texture._sphericalPolynomial =
  22263. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  22264. }
  22265. return this._texture._sphericalPolynomial;
  22266. },
  22267. set: function (value) {
  22268. if (this._texture) {
  22269. this._texture._sphericalPolynomial = value;
  22270. }
  22271. },
  22272. enumerable: true,
  22273. configurable: true
  22274. });
  22275. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  22276. get: function () {
  22277. if (this._texture) {
  22278. return this._texture._lodTextureHigh;
  22279. }
  22280. return null;
  22281. },
  22282. enumerable: true,
  22283. configurable: true
  22284. });
  22285. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  22286. get: function () {
  22287. if (this._texture) {
  22288. return this._texture._lodTextureMid;
  22289. }
  22290. return null;
  22291. },
  22292. enumerable: true,
  22293. configurable: true
  22294. });
  22295. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  22296. get: function () {
  22297. if (this._texture) {
  22298. return this._texture._lodTextureLow;
  22299. }
  22300. return null;
  22301. },
  22302. enumerable: true,
  22303. configurable: true
  22304. });
  22305. BaseTexture.prototype.dispose = function () {
  22306. if (!this._scene) {
  22307. return;
  22308. }
  22309. // Animations
  22310. this._scene.stopAnimation(this);
  22311. // Remove from scene
  22312. this._scene._removePendingData(this);
  22313. var index = this._scene.textures.indexOf(this);
  22314. if (index >= 0) {
  22315. this._scene.textures.splice(index, 1);
  22316. }
  22317. if (this._texture === undefined) {
  22318. return;
  22319. }
  22320. // Release
  22321. this.releaseInternalTexture();
  22322. // Callback
  22323. this.onDisposeObservable.notifyObservers(this);
  22324. this.onDisposeObservable.clear();
  22325. };
  22326. BaseTexture.prototype.serialize = function () {
  22327. if (!this.name) {
  22328. return null;
  22329. }
  22330. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22331. // Animations
  22332. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22333. return serializationObject;
  22334. };
  22335. BaseTexture.WhenAllReady = function (textures, callback) {
  22336. var numRemaining = textures.length;
  22337. if (numRemaining === 0) {
  22338. callback();
  22339. return;
  22340. }
  22341. var _loop_1 = function () {
  22342. texture = textures[i];
  22343. if (texture.isReady()) {
  22344. if (--numRemaining === 0) {
  22345. callback();
  22346. }
  22347. }
  22348. else {
  22349. onLoadObservable = texture.onLoadObservable;
  22350. var onLoadCallback_1 = function () {
  22351. onLoadObservable.removeCallback(onLoadCallback_1);
  22352. if (--numRemaining === 0) {
  22353. callback();
  22354. }
  22355. };
  22356. onLoadObservable.add(onLoadCallback_1);
  22357. }
  22358. };
  22359. var texture, onLoadObservable;
  22360. for (var i = 0; i < textures.length; i++) {
  22361. _loop_1();
  22362. }
  22363. };
  22364. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  22365. __decorate([
  22366. BABYLON.serialize()
  22367. ], BaseTexture.prototype, "name", void 0);
  22368. __decorate([
  22369. BABYLON.serialize("hasAlpha")
  22370. ], BaseTexture.prototype, "_hasAlpha", void 0);
  22371. __decorate([
  22372. BABYLON.serialize()
  22373. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  22374. __decorate([
  22375. BABYLON.serialize()
  22376. ], BaseTexture.prototype, "level", void 0);
  22377. __decorate([
  22378. BABYLON.serialize()
  22379. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  22380. __decorate([
  22381. BABYLON.serialize("coordinatesMode")
  22382. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  22383. __decorate([
  22384. BABYLON.serialize()
  22385. ], BaseTexture.prototype, "wrapU", void 0);
  22386. __decorate([
  22387. BABYLON.serialize()
  22388. ], BaseTexture.prototype, "wrapV", void 0);
  22389. __decorate([
  22390. BABYLON.serialize()
  22391. ], BaseTexture.prototype, "wrapR", void 0);
  22392. __decorate([
  22393. BABYLON.serialize()
  22394. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  22395. __decorate([
  22396. BABYLON.serialize()
  22397. ], BaseTexture.prototype, "isCube", void 0);
  22398. __decorate([
  22399. BABYLON.serialize()
  22400. ], BaseTexture.prototype, "is3D", void 0);
  22401. __decorate([
  22402. BABYLON.serialize()
  22403. ], BaseTexture.prototype, "gammaSpace", void 0);
  22404. __decorate([
  22405. BABYLON.serialize()
  22406. ], BaseTexture.prototype, "invertZ", void 0);
  22407. __decorate([
  22408. BABYLON.serialize()
  22409. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  22410. __decorate([
  22411. BABYLON.serialize()
  22412. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  22413. __decorate([
  22414. BABYLON.serialize()
  22415. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  22416. __decorate([
  22417. BABYLON.serialize()
  22418. ], BaseTexture.prototype, "isRenderTarget", void 0);
  22419. return BaseTexture;
  22420. }());
  22421. BABYLON.BaseTexture = BaseTexture;
  22422. })(BABYLON || (BABYLON = {}));
  22423. //# sourceMappingURL=babylon.baseTexture.js.map
  22424. var BABYLON;
  22425. (function (BABYLON) {
  22426. var Texture = /** @class */ (function (_super) {
  22427. __extends(Texture, _super);
  22428. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  22429. if (noMipmap === void 0) { noMipmap = false; }
  22430. if (invertY === void 0) { invertY = true; }
  22431. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22432. if (onLoad === void 0) { onLoad = null; }
  22433. if (onError === void 0) { onError = null; }
  22434. if (buffer === void 0) { buffer = null; }
  22435. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22436. var _this = _super.call(this, scene) || this;
  22437. _this.uOffset = 0;
  22438. _this.vOffset = 0;
  22439. _this.uScale = 1.0;
  22440. _this.vScale = 1.0;
  22441. _this.uAng = 0;
  22442. _this.vAng = 0;
  22443. _this.wAng = 0;
  22444. _this._isBlocking = true;
  22445. _this.name = url || "";
  22446. _this.url = url;
  22447. _this._noMipmap = noMipmap;
  22448. _this._invertY = invertY;
  22449. _this._samplingMode = samplingMode;
  22450. _this._buffer = buffer;
  22451. _this._deleteBuffer = deleteBuffer;
  22452. if (format) {
  22453. _this._format = format;
  22454. }
  22455. scene = _this.getScene();
  22456. if (!scene) {
  22457. return _this;
  22458. }
  22459. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  22460. var load = function () {
  22461. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  22462. _this.onLoadObservable.notifyObservers(_this);
  22463. }
  22464. if (onLoad) {
  22465. onLoad();
  22466. }
  22467. if (!_this.isBlocking && scene) {
  22468. scene.resetCachedMaterial();
  22469. }
  22470. };
  22471. if (!_this.url) {
  22472. _this._delayedOnLoad = load;
  22473. _this._delayedOnError = onError;
  22474. return _this;
  22475. }
  22476. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  22477. if (!_this._texture) {
  22478. if (!scene.useDelayedTextureLoading) {
  22479. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  22480. if (deleteBuffer) {
  22481. delete _this._buffer;
  22482. }
  22483. }
  22484. else {
  22485. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22486. _this._delayedOnLoad = load;
  22487. _this._delayedOnError = onError;
  22488. }
  22489. }
  22490. else {
  22491. if (_this._texture.isReady) {
  22492. BABYLON.Tools.SetImmediate(function () { return load(); });
  22493. }
  22494. else {
  22495. _this._texture.onLoadedObservable.add(load);
  22496. }
  22497. }
  22498. return _this;
  22499. }
  22500. Object.defineProperty(Texture.prototype, "noMipmap", {
  22501. get: function () {
  22502. return this._noMipmap;
  22503. },
  22504. enumerable: true,
  22505. configurable: true
  22506. });
  22507. Object.defineProperty(Texture.prototype, "isBlocking", {
  22508. get: function () {
  22509. return this._isBlocking;
  22510. },
  22511. set: function (value) {
  22512. this._isBlocking = value;
  22513. },
  22514. enumerable: true,
  22515. configurable: true
  22516. });
  22517. Object.defineProperty(Texture.prototype, "samplingMode", {
  22518. get: function () {
  22519. return this._samplingMode;
  22520. },
  22521. enumerable: true,
  22522. configurable: true
  22523. });
  22524. Texture.prototype.updateURL = function (url) {
  22525. this.url = url;
  22526. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22527. this.delayLoad();
  22528. };
  22529. Texture.prototype.delayLoad = function () {
  22530. var _this = this;
  22531. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22532. return;
  22533. }
  22534. var scene = this.getScene();
  22535. if (!scene) {
  22536. return;
  22537. }
  22538. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22539. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  22540. if (!this._texture) {
  22541. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  22542. if (this._deleteBuffer) {
  22543. delete this._buffer;
  22544. }
  22545. }
  22546. else {
  22547. if (this._texture.isReady) {
  22548. BABYLON.Tools.SetImmediate(function () {
  22549. if (!_this._delayedOnLoad) {
  22550. return;
  22551. }
  22552. _this._delayedOnLoad();
  22553. });
  22554. }
  22555. else {
  22556. if (this._delayedOnLoad) {
  22557. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  22558. }
  22559. }
  22560. }
  22561. };
  22562. Texture.prototype.updateSamplingMode = function (samplingMode) {
  22563. if (!this._texture) {
  22564. return;
  22565. }
  22566. var scene = this.getScene();
  22567. if (!scene) {
  22568. return;
  22569. }
  22570. this._samplingMode = samplingMode;
  22571. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  22572. };
  22573. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  22574. x *= this.uScale;
  22575. y *= this.vScale;
  22576. x -= 0.5 * this.uScale;
  22577. y -= 0.5 * this.vScale;
  22578. z -= 0.5;
  22579. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  22580. t.x += 0.5 * this.uScale + this.uOffset;
  22581. t.y += 0.5 * this.vScale + this.vOffset;
  22582. t.z += 0.5;
  22583. };
  22584. Texture.prototype.getTextureMatrix = function () {
  22585. var _this = this;
  22586. if (this.uOffset === this._cachedUOffset &&
  22587. this.vOffset === this._cachedVOffset &&
  22588. this.uScale === this._cachedUScale &&
  22589. this.vScale === this._cachedVScale &&
  22590. this.uAng === this._cachedUAng &&
  22591. this.vAng === this._cachedVAng &&
  22592. this.wAng === this._cachedWAng) {
  22593. return this._cachedTextureMatrix;
  22594. }
  22595. this._cachedUOffset = this.uOffset;
  22596. this._cachedVOffset = this.vOffset;
  22597. this._cachedUScale = this.uScale;
  22598. this._cachedVScale = this.vScale;
  22599. this._cachedUAng = this.uAng;
  22600. this._cachedVAng = this.vAng;
  22601. this._cachedWAng = this.wAng;
  22602. if (!this._cachedTextureMatrix) {
  22603. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22604. this._rowGenerationMatrix = new BABYLON.Matrix();
  22605. this._t0 = BABYLON.Vector3.Zero();
  22606. this._t1 = BABYLON.Vector3.Zero();
  22607. this._t2 = BABYLON.Vector3.Zero();
  22608. }
  22609. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  22610. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  22611. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  22612. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  22613. this._t1.subtractInPlace(this._t0);
  22614. this._t2.subtractInPlace(this._t0);
  22615. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22616. this._cachedTextureMatrix.m[0] = this._t1.x;
  22617. this._cachedTextureMatrix.m[1] = this._t1.y;
  22618. this._cachedTextureMatrix.m[2] = this._t1.z;
  22619. this._cachedTextureMatrix.m[4] = this._t2.x;
  22620. this._cachedTextureMatrix.m[5] = this._t2.y;
  22621. this._cachedTextureMatrix.m[6] = this._t2.z;
  22622. this._cachedTextureMatrix.m[8] = this._t0.x;
  22623. this._cachedTextureMatrix.m[9] = this._t0.y;
  22624. this._cachedTextureMatrix.m[10] = this._t0.z;
  22625. var scene = this.getScene();
  22626. if (!scene) {
  22627. return this._cachedTextureMatrix;
  22628. }
  22629. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22630. return mat.hasTexture(_this);
  22631. });
  22632. return this._cachedTextureMatrix;
  22633. };
  22634. Texture.prototype.getReflectionTextureMatrix = function () {
  22635. var _this = this;
  22636. var scene = this.getScene();
  22637. if (!scene) {
  22638. return this._cachedTextureMatrix;
  22639. }
  22640. if (this.uOffset === this._cachedUOffset &&
  22641. this.vOffset === this._cachedVOffset &&
  22642. this.uScale === this._cachedUScale &&
  22643. this.vScale === this._cachedVScale &&
  22644. this.coordinatesMode === this._cachedCoordinatesMode) {
  22645. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  22646. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  22647. return this._cachedTextureMatrix;
  22648. }
  22649. }
  22650. else {
  22651. return this._cachedTextureMatrix;
  22652. }
  22653. }
  22654. if (!this._cachedTextureMatrix) {
  22655. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22656. }
  22657. if (!this._projectionModeMatrix) {
  22658. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  22659. }
  22660. this._cachedUOffset = this.uOffset;
  22661. this._cachedVOffset = this.vOffset;
  22662. this._cachedUScale = this.uScale;
  22663. this._cachedVScale = this.vScale;
  22664. this._cachedCoordinatesMode = this.coordinatesMode;
  22665. switch (this.coordinatesMode) {
  22666. case Texture.PLANAR_MODE:
  22667. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22668. this._cachedTextureMatrix[0] = this.uScale;
  22669. this._cachedTextureMatrix[5] = this.vScale;
  22670. this._cachedTextureMatrix[12] = this.uOffset;
  22671. this._cachedTextureMatrix[13] = this.vOffset;
  22672. break;
  22673. case Texture.PROJECTION_MODE:
  22674. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  22675. this._projectionModeMatrix.m[0] = 0.5;
  22676. this._projectionModeMatrix.m[5] = -0.5;
  22677. this._projectionModeMatrix.m[10] = 0.0;
  22678. this._projectionModeMatrix.m[12] = 0.5;
  22679. this._projectionModeMatrix.m[13] = 0.5;
  22680. this._projectionModeMatrix.m[14] = 1.0;
  22681. this._projectionModeMatrix.m[15] = 1.0;
  22682. var projectionMatrix = scene.getProjectionMatrix();
  22683. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  22684. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  22685. break;
  22686. default:
  22687. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22688. break;
  22689. }
  22690. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22691. return (mat.getActiveTextures().indexOf(_this) !== -1);
  22692. });
  22693. return this._cachedTextureMatrix;
  22694. };
  22695. Texture.prototype.clone = function () {
  22696. var _this = this;
  22697. return BABYLON.SerializationHelper.Clone(function () {
  22698. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  22699. }, this);
  22700. };
  22701. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  22702. get: function () {
  22703. if (!this._onLoadObservable) {
  22704. this._onLoadObservable = new BABYLON.Observable();
  22705. }
  22706. return this._onLoadObservable;
  22707. },
  22708. enumerable: true,
  22709. configurable: true
  22710. });
  22711. Texture.prototype.serialize = function () {
  22712. var serializationObject = _super.prototype.serialize.call(this);
  22713. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  22714. serializationObject.base64String = this._buffer;
  22715. serializationObject.name = serializationObject.name.replace("data:", "");
  22716. }
  22717. return serializationObject;
  22718. };
  22719. Texture.prototype.getClassName = function () {
  22720. return "Texture";
  22721. };
  22722. Texture.prototype.dispose = function () {
  22723. _super.prototype.dispose.call(this);
  22724. if (this.onLoadObservable) {
  22725. this.onLoadObservable.clear();
  22726. this._onLoadObservable = null;
  22727. }
  22728. this._delayedOnLoad = null;
  22729. this._delayedOnError = null;
  22730. };
  22731. // Statics
  22732. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22733. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22734. if (onLoad === void 0) { onLoad = null; }
  22735. if (onError === void 0) { onError = null; }
  22736. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22737. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  22738. };
  22739. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  22740. if (parsedTexture.customType) {
  22741. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  22742. // Update Sampling Mode
  22743. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  22744. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  22745. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  22746. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  22747. }
  22748. }
  22749. return parsedCustomTexture;
  22750. }
  22751. if (parsedTexture.isCube) {
  22752. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  22753. }
  22754. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  22755. return null;
  22756. }
  22757. var texture = BABYLON.SerializationHelper.Parse(function () {
  22758. var generateMipMaps = true;
  22759. if (parsedTexture.noMipmap) {
  22760. generateMipMaps = false;
  22761. }
  22762. if (parsedTexture.mirrorPlane) {
  22763. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  22764. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  22765. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  22766. return mirrorTexture;
  22767. }
  22768. else if (parsedTexture.isRenderTarget) {
  22769. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  22770. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  22771. return renderTargetTexture;
  22772. }
  22773. else {
  22774. var texture;
  22775. if (parsedTexture.base64String) {
  22776. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  22777. }
  22778. else {
  22779. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  22780. }
  22781. return texture;
  22782. }
  22783. }, parsedTexture, scene);
  22784. // Update Sampling Mode
  22785. if (parsedTexture.samplingMode) {
  22786. var sampling = parsedTexture.samplingMode;
  22787. if (texture._samplingMode !== sampling) {
  22788. texture.updateSamplingMode(sampling);
  22789. }
  22790. }
  22791. // Animations
  22792. if (parsedTexture.animations) {
  22793. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22794. var parsedAnimation = parsedTexture.animations[animationIndex];
  22795. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22796. }
  22797. }
  22798. return texture;
  22799. };
  22800. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22801. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22802. if (noMipmap === void 0) { noMipmap = false; }
  22803. if (invertY === void 0) { invertY = true; }
  22804. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22805. if (onLoad === void 0) { onLoad = null; }
  22806. if (onError === void 0) { onError = null; }
  22807. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22808. if (name.substr(0, 5) !== "data:") {
  22809. name = "data:" + name;
  22810. }
  22811. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  22812. };
  22813. // Constants
  22814. Texture.NEAREST_SAMPLINGMODE = 1;
  22815. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  22816. Texture.BILINEAR_SAMPLINGMODE = 2;
  22817. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  22818. Texture.TRILINEAR_SAMPLINGMODE = 3;
  22819. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  22820. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  22821. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  22822. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  22823. Texture.NEAREST_LINEAR = 7;
  22824. Texture.NEAREST_NEAREST = 8;
  22825. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  22826. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  22827. Texture.LINEAR_LINEAR = 11;
  22828. Texture.LINEAR_NEAREST = 12;
  22829. Texture.EXPLICIT_MODE = 0;
  22830. Texture.SPHERICAL_MODE = 1;
  22831. Texture.PLANAR_MODE = 2;
  22832. Texture.CUBIC_MODE = 3;
  22833. Texture.PROJECTION_MODE = 4;
  22834. Texture.SKYBOX_MODE = 5;
  22835. Texture.INVCUBIC_MODE = 6;
  22836. Texture.EQUIRECTANGULAR_MODE = 7;
  22837. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  22838. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  22839. Texture.CLAMP_ADDRESSMODE = 0;
  22840. Texture.WRAP_ADDRESSMODE = 1;
  22841. Texture.MIRROR_ADDRESSMODE = 2;
  22842. __decorate([
  22843. BABYLON.serialize()
  22844. ], Texture.prototype, "url", void 0);
  22845. __decorate([
  22846. BABYLON.serialize()
  22847. ], Texture.prototype, "uOffset", void 0);
  22848. __decorate([
  22849. BABYLON.serialize()
  22850. ], Texture.prototype, "vOffset", void 0);
  22851. __decorate([
  22852. BABYLON.serialize()
  22853. ], Texture.prototype, "uScale", void 0);
  22854. __decorate([
  22855. BABYLON.serialize()
  22856. ], Texture.prototype, "vScale", void 0);
  22857. __decorate([
  22858. BABYLON.serialize()
  22859. ], Texture.prototype, "uAng", void 0);
  22860. __decorate([
  22861. BABYLON.serialize()
  22862. ], Texture.prototype, "vAng", void 0);
  22863. __decorate([
  22864. BABYLON.serialize()
  22865. ], Texture.prototype, "wAng", void 0);
  22866. __decorate([
  22867. BABYLON.serialize()
  22868. ], Texture.prototype, "isBlocking", null);
  22869. return Texture;
  22870. }(BABYLON.BaseTexture));
  22871. BABYLON.Texture = Texture;
  22872. })(BABYLON || (BABYLON = {}));
  22873. //# sourceMappingURL=babylon.texture.js.map
  22874. var BABYLON;
  22875. (function (BABYLON) {
  22876. var _InstancesBatch = /** @class */ (function () {
  22877. function _InstancesBatch() {
  22878. this.mustReturn = false;
  22879. this.visibleInstances = new Array();
  22880. this.renderSelf = new Array();
  22881. }
  22882. return _InstancesBatch;
  22883. }());
  22884. BABYLON._InstancesBatch = _InstancesBatch;
  22885. var Mesh = /** @class */ (function (_super) {
  22886. __extends(Mesh, _super);
  22887. /**
  22888. * @constructor
  22889. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  22890. * @param {Scene} scene The scene to add this mesh to.
  22891. * @param {Node} parent The parent of this mesh, if it has one
  22892. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  22893. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  22894. * When false, achieved by calling a clone(), also passing False.
  22895. * This will make creation of children, recursive.
  22896. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  22897. */
  22898. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  22899. if (scene === void 0) { scene = null; }
  22900. if (parent === void 0) { parent = null; }
  22901. if (source === void 0) { source = null; }
  22902. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22903. var _this = _super.call(this, name, scene) || this;
  22904. // Events
  22905. /**
  22906. * An event triggered before rendering the mesh
  22907. * @type {BABYLON.Observable}
  22908. */
  22909. _this.onBeforeRenderObservable = new BABYLON.Observable();
  22910. /**
  22911. * An event triggered after rendering the mesh
  22912. * @type {BABYLON.Observable}
  22913. */
  22914. _this.onAfterRenderObservable = new BABYLON.Observable();
  22915. /**
  22916. * An event triggered before drawing the mesh
  22917. * @type {BABYLON.Observable}
  22918. */
  22919. _this.onBeforeDrawObservable = new BABYLON.Observable();
  22920. // Members
  22921. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22922. _this.instances = new Array();
  22923. _this._LODLevels = new Array();
  22924. _this._visibleInstances = {};
  22925. _this._renderIdForInstances = new Array();
  22926. _this._batchCache = new _InstancesBatch();
  22927. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  22928. // Use by builder only to know what orientation were the mesh build in.
  22929. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  22930. _this.overrideMaterialSideOrientation = null;
  22931. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  22932. // Will be used to save a source mesh reference, If any
  22933. _this._source = null;
  22934. scene = _this.getScene();
  22935. if (source) {
  22936. // Source mesh
  22937. _this._source = source;
  22938. // Geometry
  22939. if (source._geometry) {
  22940. source._geometry.applyToMesh(_this);
  22941. }
  22942. // Deep copy
  22943. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source"], ["_poseMatrix", "_source"]);
  22944. // Tags
  22945. if (BABYLON.Tags.HasTags(source)) {
  22946. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  22947. }
  22948. _this.metadata = source.metadata;
  22949. // Parent
  22950. _this.parent = source.parent;
  22951. // Pivot
  22952. _this.setPivotMatrix(source.getPivotMatrix());
  22953. _this.id = name + "." + source.id;
  22954. // Material
  22955. _this.material = source.material;
  22956. var index;
  22957. if (!doNotCloneChildren) {
  22958. // Children
  22959. for (index = 0; index < scene.meshes.length; index++) {
  22960. var mesh = scene.meshes[index];
  22961. if (mesh.parent === source) {
  22962. // doNotCloneChildren is always going to be False
  22963. mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  22964. }
  22965. }
  22966. }
  22967. // Physics clone
  22968. var physicsEngine = _this.getScene().getPhysicsEngine();
  22969. if (clonePhysicsImpostor && physicsEngine) {
  22970. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  22971. if (impostor) {
  22972. _this.physicsImpostor = impostor.clone(_this);
  22973. }
  22974. }
  22975. // Particles
  22976. for (index = 0; index < scene.particleSystems.length; index++) {
  22977. var system = scene.particleSystems[index];
  22978. if (system.emitter === source) {
  22979. system.clone(system.name, _this);
  22980. }
  22981. }
  22982. _this.computeWorldMatrix(true);
  22983. }
  22984. // Parent
  22985. if (parent !== null) {
  22986. _this.parent = parent;
  22987. }
  22988. return _this;
  22989. }
  22990. Object.defineProperty(Mesh, "FRONTSIDE", {
  22991. /**
  22992. * Mesh side orientation : usually the external or front surface
  22993. */
  22994. get: function () {
  22995. return Mesh._FRONTSIDE;
  22996. },
  22997. enumerable: true,
  22998. configurable: true
  22999. });
  23000. Object.defineProperty(Mesh, "BACKSIDE", {
  23001. /**
  23002. * Mesh side orientation : usually the internal or back surface
  23003. */
  23004. get: function () {
  23005. return Mesh._BACKSIDE;
  23006. },
  23007. enumerable: true,
  23008. configurable: true
  23009. });
  23010. Object.defineProperty(Mesh, "DOUBLESIDE", {
  23011. /**
  23012. * Mesh side orientation : both internal and external or front and back surfaces
  23013. */
  23014. get: function () {
  23015. return Mesh._DOUBLESIDE;
  23016. },
  23017. enumerable: true,
  23018. configurable: true
  23019. });
  23020. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  23021. /**
  23022. * Mesh side orientation : by default, `FRONTSIDE`
  23023. */
  23024. get: function () {
  23025. return Mesh._DEFAULTSIDE;
  23026. },
  23027. enumerable: true,
  23028. configurable: true
  23029. });
  23030. Object.defineProperty(Mesh, "NO_CAP", {
  23031. /**
  23032. * Mesh cap setting : no cap
  23033. */
  23034. get: function () {
  23035. return Mesh._NO_CAP;
  23036. },
  23037. enumerable: true,
  23038. configurable: true
  23039. });
  23040. Object.defineProperty(Mesh, "CAP_START", {
  23041. /**
  23042. * Mesh cap setting : one cap at the beginning of the mesh
  23043. */
  23044. get: function () {
  23045. return Mesh._CAP_START;
  23046. },
  23047. enumerable: true,
  23048. configurable: true
  23049. });
  23050. Object.defineProperty(Mesh, "CAP_END", {
  23051. /**
  23052. * Mesh cap setting : one cap at the end of the mesh
  23053. */
  23054. get: function () {
  23055. return Mesh._CAP_END;
  23056. },
  23057. enumerable: true,
  23058. configurable: true
  23059. });
  23060. Object.defineProperty(Mesh, "CAP_ALL", {
  23061. /**
  23062. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  23063. */
  23064. get: function () {
  23065. return Mesh._CAP_ALL;
  23066. },
  23067. enumerable: true,
  23068. configurable: true
  23069. });
  23070. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  23071. set: function (callback) {
  23072. if (this._onBeforeDrawObserver) {
  23073. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  23074. }
  23075. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  23076. },
  23077. enumerable: true,
  23078. configurable: true
  23079. });
  23080. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  23081. get: function () {
  23082. return this._morphTargetManager;
  23083. },
  23084. set: function (value) {
  23085. if (this._morphTargetManager === value) {
  23086. return;
  23087. }
  23088. this._morphTargetManager = value;
  23089. this._syncGeometryWithMorphTargetManager();
  23090. },
  23091. enumerable: true,
  23092. configurable: true
  23093. });
  23094. Object.defineProperty(Mesh.prototype, "source", {
  23095. get: function () {
  23096. return this._source;
  23097. },
  23098. enumerable: true,
  23099. configurable: true
  23100. });
  23101. // Methods
  23102. /**
  23103. * Returns the string "Mesh".
  23104. */
  23105. Mesh.prototype.getClassName = function () {
  23106. return "Mesh";
  23107. };
  23108. /**
  23109. * Returns a string.
  23110. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23111. */
  23112. Mesh.prototype.toString = function (fullDetails) {
  23113. var ret = _super.prototype.toString.call(this, fullDetails);
  23114. ret += ", n vertices: " + this.getTotalVertices();
  23115. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  23116. if (this.animations) {
  23117. for (var i = 0; i < this.animations.length; i++) {
  23118. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23119. }
  23120. }
  23121. if (fullDetails) {
  23122. if (this._geometry) {
  23123. var ib = this.getIndices();
  23124. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23125. if (vb && ib) {
  23126. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  23127. }
  23128. }
  23129. else {
  23130. ret += ", flat shading: UNKNOWN";
  23131. }
  23132. }
  23133. return ret;
  23134. };
  23135. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  23136. /**
  23137. * True if the mesh has some Levels Of Details (LOD).
  23138. * Returns a boolean.
  23139. */
  23140. get: function () {
  23141. return this._LODLevels.length > 0;
  23142. },
  23143. enumerable: true,
  23144. configurable: true
  23145. });
  23146. Mesh.prototype._sortLODLevels = function () {
  23147. this._LODLevels.sort(function (a, b) {
  23148. if (a.distance < b.distance) {
  23149. return 1;
  23150. }
  23151. if (a.distance > b.distance) {
  23152. return -1;
  23153. }
  23154. return 0;
  23155. });
  23156. };
  23157. /**
  23158. * Add a mesh as LOD level triggered at the given distance.
  23159. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23160. * @param {number} distance The distance from the center of the object to show this level
  23161. * @param {Mesh} mesh The mesh to be added as LOD level
  23162. * @return {Mesh} This mesh (for chaining)
  23163. */
  23164. Mesh.prototype.addLODLevel = function (distance, mesh) {
  23165. if (mesh && mesh._masterMesh) {
  23166. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  23167. return this;
  23168. }
  23169. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  23170. this._LODLevels.push(level);
  23171. if (mesh) {
  23172. mesh._masterMesh = this;
  23173. }
  23174. this._sortLODLevels();
  23175. return this;
  23176. };
  23177. /**
  23178. * Returns the LOD level mesh at the passed distance or null if not found.
  23179. * It is related to the method `addLODLevel(distance, mesh)`.
  23180. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23181. * Returns an object Mesh or `null`.
  23182. */
  23183. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  23184. for (var index = 0; index < this._LODLevels.length; index++) {
  23185. var level = this._LODLevels[index];
  23186. if (level.distance === distance) {
  23187. return level.mesh;
  23188. }
  23189. }
  23190. return null;
  23191. };
  23192. /**
  23193. * Remove a mesh from the LOD array
  23194. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23195. * @param {Mesh} mesh The mesh to be removed.
  23196. * @return {Mesh} This mesh (for chaining)
  23197. */
  23198. Mesh.prototype.removeLODLevel = function (mesh) {
  23199. for (var index = 0; index < this._LODLevels.length; index++) {
  23200. if (this._LODLevels[index].mesh === mesh) {
  23201. this._LODLevels.splice(index, 1);
  23202. if (mesh) {
  23203. mesh._masterMesh = null;
  23204. }
  23205. }
  23206. }
  23207. this._sortLODLevels();
  23208. return this;
  23209. };
  23210. /**
  23211. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  23212. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23213. */
  23214. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  23215. if (!this._LODLevels || this._LODLevels.length === 0) {
  23216. return this;
  23217. }
  23218. var bSphere;
  23219. if (boundingSphere) {
  23220. bSphere = boundingSphere;
  23221. }
  23222. else {
  23223. var boundingInfo = this.getBoundingInfo();
  23224. bSphere = boundingInfo.boundingSphere;
  23225. }
  23226. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  23227. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  23228. if (this.onLODLevelSelection) {
  23229. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  23230. }
  23231. return this;
  23232. }
  23233. for (var index = 0; index < this._LODLevels.length; index++) {
  23234. var level = this._LODLevels[index];
  23235. if (level.distance < distanceToCamera) {
  23236. if (level.mesh) {
  23237. level.mesh._preActivate();
  23238. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  23239. }
  23240. if (this.onLODLevelSelection) {
  23241. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  23242. }
  23243. return level.mesh;
  23244. }
  23245. }
  23246. if (this.onLODLevelSelection) {
  23247. this.onLODLevelSelection(distanceToCamera, this, this);
  23248. }
  23249. return this;
  23250. };
  23251. Object.defineProperty(Mesh.prototype, "geometry", {
  23252. /**
  23253. * Returns the mesh internal Geometry object.
  23254. */
  23255. get: function () {
  23256. return this._geometry;
  23257. },
  23258. enumerable: true,
  23259. configurable: true
  23260. });
  23261. /**
  23262. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  23263. */
  23264. Mesh.prototype.getTotalVertices = function () {
  23265. if (!this._geometry) {
  23266. return 0;
  23267. }
  23268. return this._geometry.getTotalVertices();
  23269. };
  23270. /**
  23271. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  23272. * 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.
  23273. * You can force the copy with forceCopy === true
  23274. * Returns null if the mesh has no geometry or no vertex buffer.
  23275. * Possible `kind` values :
  23276. * - BABYLON.VertexBuffer.PositionKind
  23277. * - BABYLON.VertexBuffer.UVKind
  23278. * - BABYLON.VertexBuffer.UV2Kind
  23279. * - BABYLON.VertexBuffer.UV3Kind
  23280. * - BABYLON.VertexBuffer.UV4Kind
  23281. * - BABYLON.VertexBuffer.UV5Kind
  23282. * - BABYLON.VertexBuffer.UV6Kind
  23283. * - BABYLON.VertexBuffer.ColorKind
  23284. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23285. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23286. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23287. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23288. */
  23289. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  23290. if (!this._geometry) {
  23291. return null;
  23292. }
  23293. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  23294. };
  23295. /**
  23296. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  23297. * Returns `null` if the mesh has no geometry.
  23298. * Possible `kind` values :
  23299. * - BABYLON.VertexBuffer.PositionKind
  23300. * - BABYLON.VertexBuffer.UVKind
  23301. * - BABYLON.VertexBuffer.UV2Kind
  23302. * - BABYLON.VertexBuffer.UV3Kind
  23303. * - BABYLON.VertexBuffer.UV4Kind
  23304. * - BABYLON.VertexBuffer.UV5Kind
  23305. * - BABYLON.VertexBuffer.UV6Kind
  23306. * - BABYLON.VertexBuffer.ColorKind
  23307. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23308. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23309. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23310. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23311. */
  23312. Mesh.prototype.getVertexBuffer = function (kind) {
  23313. if (!this._geometry) {
  23314. return null;
  23315. }
  23316. return this._geometry.getVertexBuffer(kind);
  23317. };
  23318. /**
  23319. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  23320. * Possible `kind` values :
  23321. * - BABYLON.VertexBuffer.PositionKind
  23322. * - BABYLON.VertexBuffer.UVKind
  23323. * - BABYLON.VertexBuffer.UV2Kind
  23324. * - BABYLON.VertexBuffer.UV3Kind
  23325. * - BABYLON.VertexBuffer.UV4Kind
  23326. * - BABYLON.VertexBuffer.UV5Kind
  23327. * - BABYLON.VertexBuffer.UV6Kind
  23328. * - BABYLON.VertexBuffer.ColorKind
  23329. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23330. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23331. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23332. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23333. */
  23334. Mesh.prototype.isVerticesDataPresent = function (kind) {
  23335. if (!this._geometry) {
  23336. if (this._delayInfo) {
  23337. return this._delayInfo.indexOf(kind) !== -1;
  23338. }
  23339. return false;
  23340. }
  23341. return this._geometry.isVerticesDataPresent(kind);
  23342. };
  23343. /**
  23344. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  23345. * Possible `kind` values :
  23346. * - BABYLON.VertexBuffer.PositionKind
  23347. * - BABYLON.VertexBuffer.UVKind
  23348. * - BABYLON.VertexBuffer.UV2Kind
  23349. * - BABYLON.VertexBuffer.UV3Kind
  23350. * - BABYLON.VertexBuffer.UV4Kind
  23351. * - BABYLON.VertexBuffer.UV5Kind
  23352. * - BABYLON.VertexBuffer.UV6Kind
  23353. * - BABYLON.VertexBuffer.ColorKind
  23354. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23355. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23356. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23357. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23358. */
  23359. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  23360. if (!this._geometry) {
  23361. if (this._delayInfo) {
  23362. return this._delayInfo.indexOf(kind) !== -1;
  23363. }
  23364. return false;
  23365. }
  23366. return this._geometry.isVertexBufferUpdatable(kind);
  23367. };
  23368. /**
  23369. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  23370. * Possible `kind` values :
  23371. * - BABYLON.VertexBuffer.PositionKind
  23372. * - BABYLON.VertexBuffer.UVKind
  23373. * - BABYLON.VertexBuffer.UV2Kind
  23374. * - BABYLON.VertexBuffer.UV3Kind
  23375. * - BABYLON.VertexBuffer.UV4Kind
  23376. * - BABYLON.VertexBuffer.UV5Kind
  23377. * - BABYLON.VertexBuffer.UV6Kind
  23378. * - BABYLON.VertexBuffer.ColorKind
  23379. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23380. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23381. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23382. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23383. */
  23384. Mesh.prototype.getVerticesDataKinds = function () {
  23385. if (!this._geometry) {
  23386. var result = new Array();
  23387. if (this._delayInfo) {
  23388. this._delayInfo.forEach(function (kind, index, array) {
  23389. result.push(kind);
  23390. });
  23391. }
  23392. return result;
  23393. }
  23394. return this._geometry.getVerticesDataKinds();
  23395. };
  23396. /**
  23397. * Returns a positive integer : the total number of indices in this mesh geometry.
  23398. * Returns zero if the mesh has no geometry.
  23399. */
  23400. Mesh.prototype.getTotalIndices = function () {
  23401. if (!this._geometry) {
  23402. return 0;
  23403. }
  23404. return this._geometry.getTotalIndices();
  23405. };
  23406. /**
  23407. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  23408. * 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.
  23409. * Returns an empty array if the mesh has no geometry.
  23410. */
  23411. Mesh.prototype.getIndices = function (copyWhenShared) {
  23412. if (!this._geometry) {
  23413. return [];
  23414. }
  23415. return this._geometry.getIndices(copyWhenShared);
  23416. };
  23417. Object.defineProperty(Mesh.prototype, "isBlocked", {
  23418. get: function () {
  23419. return this._masterMesh !== null && this._masterMesh !== undefined;
  23420. },
  23421. enumerable: true,
  23422. configurable: true
  23423. });
  23424. /**
  23425. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  23426. */
  23427. Mesh.prototype.isReady = function () {
  23428. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23429. return false;
  23430. }
  23431. return _super.prototype.isReady.call(this);
  23432. };
  23433. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  23434. /**
  23435. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  23436. * This property is pertinent only for updatable parametric shapes.
  23437. */
  23438. get: function () {
  23439. return this._areNormalsFrozen;
  23440. },
  23441. enumerable: true,
  23442. configurable: true
  23443. });
  23444. /**
  23445. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23446. * It has no effect at all on other shapes.
  23447. * It prevents the mesh normals from being recomputed on next `positions` array update.
  23448. * Returns the Mesh.
  23449. */
  23450. Mesh.prototype.freezeNormals = function () {
  23451. this._areNormalsFrozen = true;
  23452. return this;
  23453. };
  23454. /**
  23455. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23456. * It has no effect at all on other shapes.
  23457. * It reactivates the mesh normals computation if it was previously frozen.
  23458. * Returns the Mesh.
  23459. */
  23460. Mesh.prototype.unfreezeNormals = function () {
  23461. this._areNormalsFrozen = false;
  23462. return this;
  23463. };
  23464. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  23465. /**
  23466. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  23467. */
  23468. set: function (count) {
  23469. this._overridenInstanceCount = count;
  23470. },
  23471. enumerable: true,
  23472. configurable: true
  23473. });
  23474. // Methods
  23475. Mesh.prototype._preActivate = function () {
  23476. var sceneRenderId = this.getScene().getRenderId();
  23477. if (this._preActivateId === sceneRenderId) {
  23478. return this;
  23479. }
  23480. this._preActivateId = sceneRenderId;
  23481. this._visibleInstances = null;
  23482. return this;
  23483. };
  23484. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  23485. if (this._visibleInstances) {
  23486. this._visibleInstances.intermediateDefaultRenderId = renderId;
  23487. }
  23488. return this;
  23489. };
  23490. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  23491. if (!this._visibleInstances) {
  23492. this._visibleInstances = {};
  23493. this._visibleInstances.defaultRenderId = renderId;
  23494. this._visibleInstances.selfDefaultRenderId = this._renderId;
  23495. }
  23496. if (!this._visibleInstances[renderId]) {
  23497. this._visibleInstances[renderId] = new Array();
  23498. }
  23499. this._visibleInstances[renderId].push(instance);
  23500. return this;
  23501. };
  23502. /**
  23503. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  23504. * This means the mesh underlying bounding box and sphere are recomputed.
  23505. * Returns the Mesh.
  23506. */
  23507. Mesh.prototype.refreshBoundingInfo = function () {
  23508. if (this._boundingInfo && this._boundingInfo.isLocked) {
  23509. return this;
  23510. }
  23511. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23512. if (data) {
  23513. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  23514. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23515. }
  23516. if (this.subMeshes) {
  23517. for (var index = 0; index < this.subMeshes.length; index++) {
  23518. this.subMeshes[index].refreshBoundingInfo();
  23519. }
  23520. }
  23521. this._updateBoundingInfo();
  23522. return this;
  23523. };
  23524. Mesh.prototype._createGlobalSubMesh = function (force) {
  23525. var totalVertices = this.getTotalVertices();
  23526. if (!totalVertices || !this.getIndices()) {
  23527. return null;
  23528. }
  23529. // Check if we need to recreate the submeshes
  23530. if (this.subMeshes && this.subMeshes.length > 0) {
  23531. var ib = this.getIndices();
  23532. if (!ib) {
  23533. return null;
  23534. }
  23535. var totalIndices = ib.length;
  23536. var needToRecreate = false;
  23537. if (force) {
  23538. needToRecreate = true;
  23539. }
  23540. else {
  23541. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  23542. var submesh = _a[_i];
  23543. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  23544. needToRecreate = true;
  23545. break;
  23546. }
  23547. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  23548. needToRecreate = true;
  23549. break;
  23550. }
  23551. }
  23552. }
  23553. if (!needToRecreate) {
  23554. return this.subMeshes[0];
  23555. }
  23556. }
  23557. this.releaseSubMeshes();
  23558. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  23559. };
  23560. Mesh.prototype.subdivide = function (count) {
  23561. if (count < 1) {
  23562. return;
  23563. }
  23564. var totalIndices = this.getTotalIndices();
  23565. var subdivisionSize = (totalIndices / count) | 0;
  23566. var offset = 0;
  23567. // Ensure that subdivisionSize is a multiple of 3
  23568. while (subdivisionSize % 3 !== 0) {
  23569. subdivisionSize++;
  23570. }
  23571. this.releaseSubMeshes();
  23572. for (var index = 0; index < count; index++) {
  23573. if (offset >= totalIndices) {
  23574. break;
  23575. }
  23576. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  23577. offset += subdivisionSize;
  23578. }
  23579. this.synchronizeInstances();
  23580. };
  23581. /**
  23582. * Sets the vertex data of the mesh geometry for the requested `kind`.
  23583. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  23584. * The `data` are either a numeric array either a Float32Array.
  23585. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  23586. * 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).
  23587. * Note that a new underlying VertexBuffer object is created each call.
  23588. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  23589. *
  23590. * Possible `kind` values :
  23591. * - BABYLON.VertexBuffer.PositionKind
  23592. * - BABYLON.VertexBuffer.UVKind
  23593. * - BABYLON.VertexBuffer.UV2Kind
  23594. * - BABYLON.VertexBuffer.UV3Kind
  23595. * - BABYLON.VertexBuffer.UV4Kind
  23596. * - BABYLON.VertexBuffer.UV5Kind
  23597. * - BABYLON.VertexBuffer.UV6Kind
  23598. * - BABYLON.VertexBuffer.ColorKind
  23599. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23600. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23601. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23602. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23603. *
  23604. * Returns the Mesh.
  23605. */
  23606. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23607. if (updatable === void 0) { updatable = false; }
  23608. if (!this._geometry) {
  23609. var vertexData = new BABYLON.VertexData();
  23610. vertexData.set(data, kind);
  23611. var scene = this.getScene();
  23612. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23613. }
  23614. else {
  23615. this._geometry.setVerticesData(kind, data, updatable, stride);
  23616. }
  23617. return this;
  23618. };
  23619. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  23620. if (updatable === void 0) { updatable = true; }
  23621. var vb = this.getVertexBuffer(kind);
  23622. if (!vb || vb.isUpdatable() === updatable) {
  23623. return;
  23624. }
  23625. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  23626. };
  23627. /**
  23628. * Sets the mesh VertexBuffer.
  23629. * Returns the Mesh.
  23630. */
  23631. Mesh.prototype.setVerticesBuffer = function (buffer) {
  23632. if (!this._geometry) {
  23633. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  23634. }
  23635. this._geometry.setVerticesBuffer(buffer);
  23636. return this;
  23637. };
  23638. /**
  23639. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  23640. * If the mesh has no geometry, it is simply returned as it is.
  23641. * The `data` are either a numeric array either a Float32Array.
  23642. * No new underlying VertexBuffer object is created.
  23643. * 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.
  23644. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  23645. *
  23646. * Possible `kind` values :
  23647. * - BABYLON.VertexBuffer.PositionKind
  23648. * - BABYLON.VertexBuffer.UVKind
  23649. * - BABYLON.VertexBuffer.UV2Kind
  23650. * - BABYLON.VertexBuffer.UV3Kind
  23651. * - BABYLON.VertexBuffer.UV4Kind
  23652. * - BABYLON.VertexBuffer.UV5Kind
  23653. * - BABYLON.VertexBuffer.UV6Kind
  23654. * - BABYLON.VertexBuffer.ColorKind
  23655. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23656. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23657. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23658. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23659. *
  23660. * Returns the Mesh.
  23661. */
  23662. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  23663. if (!this._geometry) {
  23664. return this;
  23665. }
  23666. if (!makeItUnique) {
  23667. this._geometry.updateVerticesData(kind, data, updateExtends);
  23668. }
  23669. else {
  23670. this.makeGeometryUnique();
  23671. this.updateVerticesData(kind, data, updateExtends, false);
  23672. }
  23673. return this;
  23674. };
  23675. /**
  23676. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  23677. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  23678. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  23679. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  23680. * Returns the Mesh.
  23681. */
  23682. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  23683. if (computeNormals === void 0) { computeNormals = true; }
  23684. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23685. if (!positions) {
  23686. return this;
  23687. }
  23688. positionFunction(positions);
  23689. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  23690. if (computeNormals) {
  23691. var indices = this.getIndices();
  23692. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23693. if (!normals) {
  23694. return this;
  23695. }
  23696. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  23697. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  23698. }
  23699. return this;
  23700. };
  23701. /**
  23702. * Creates a un-shared specific occurence of the geometry for the mesh.
  23703. * Returns the Mesh.
  23704. */
  23705. Mesh.prototype.makeGeometryUnique = function () {
  23706. if (!this._geometry) {
  23707. return this;
  23708. }
  23709. var oldGeometry = this._geometry;
  23710. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  23711. oldGeometry.releaseForMesh(this, true);
  23712. geometry.applyToMesh(this);
  23713. return this;
  23714. };
  23715. /**
  23716. * Sets the mesh indices.
  23717. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  23718. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  23719. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  23720. * This method creates a new index buffer each call.
  23721. * Returns the Mesh.
  23722. */
  23723. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  23724. if (totalVertices === void 0) { totalVertices = null; }
  23725. if (updatable === void 0) { updatable = false; }
  23726. if (!this._geometry) {
  23727. var vertexData = new BABYLON.VertexData();
  23728. vertexData.indices = indices;
  23729. var scene = this.getScene();
  23730. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23731. }
  23732. else {
  23733. this._geometry.setIndices(indices, totalVertices, updatable);
  23734. }
  23735. return this;
  23736. };
  23737. /**
  23738. * Update the current index buffer
  23739. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  23740. * Returns the Mesh.
  23741. */
  23742. Mesh.prototype.updateIndices = function (indices, offset) {
  23743. if (!this._geometry) {
  23744. return this;
  23745. }
  23746. this._geometry.updateIndices(indices, offset);
  23747. return this;
  23748. };
  23749. /**
  23750. * Invert the geometry to move from a right handed system to a left handed one.
  23751. * Returns the Mesh.
  23752. */
  23753. Mesh.prototype.toLeftHanded = function () {
  23754. if (!this._geometry) {
  23755. return this;
  23756. }
  23757. this._geometry.toLeftHanded();
  23758. return this;
  23759. };
  23760. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  23761. if (!this._geometry) {
  23762. return this;
  23763. }
  23764. var engine = this.getScene().getEngine();
  23765. // Wireframe
  23766. var indexToBind;
  23767. if (this._unIndexed) {
  23768. indexToBind = null;
  23769. }
  23770. else {
  23771. switch (fillMode) {
  23772. case BABYLON.Material.PointFillMode:
  23773. indexToBind = null;
  23774. break;
  23775. case BABYLON.Material.WireFrameFillMode:
  23776. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  23777. break;
  23778. default:
  23779. case BABYLON.Material.TriangleFillMode:
  23780. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  23781. break;
  23782. }
  23783. }
  23784. // VBOs
  23785. this._geometry._bind(effect, indexToBind);
  23786. return this;
  23787. };
  23788. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  23789. if (alternate === void 0) { alternate = false; }
  23790. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23791. return this;
  23792. }
  23793. this.onBeforeDrawObservable.notifyObservers(this);
  23794. var scene = this.getScene();
  23795. var engine = scene.getEngine();
  23796. // Draw order
  23797. switch (fillMode) {
  23798. case BABYLON.Material.PointFillMode:
  23799. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23800. break;
  23801. case BABYLON.Material.WireFrameFillMode:
  23802. if (this._unIndexed) {
  23803. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23804. }
  23805. else {
  23806. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  23807. }
  23808. break;
  23809. default:
  23810. if (this._unIndexed) {
  23811. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23812. }
  23813. else {
  23814. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  23815. }
  23816. }
  23817. if (scene._isAlternateRenderingEnabled && !alternate) {
  23818. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  23819. if (!effect || !scene.activeCamera) {
  23820. return this;
  23821. }
  23822. scene._switchToAlternateCameraConfiguration(true);
  23823. this._effectiveMaterial.bindView(effect);
  23824. this._effectiveMaterial.bindViewProjection(effect);
  23825. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  23826. this._draw(subMesh, fillMode, instancesCount, true);
  23827. engine.setViewport(scene.activeCamera.viewport);
  23828. scene._switchToAlternateCameraConfiguration(false);
  23829. this._effectiveMaterial.bindView(effect);
  23830. this._effectiveMaterial.bindViewProjection(effect);
  23831. }
  23832. return this;
  23833. };
  23834. /**
  23835. * Registers for this mesh a javascript function called just before the rendering process.
  23836. * This function is passed the current mesh.
  23837. * Return the Mesh.
  23838. */
  23839. Mesh.prototype.registerBeforeRender = function (func) {
  23840. this.onBeforeRenderObservable.add(func);
  23841. return this;
  23842. };
  23843. /**
  23844. * Disposes a previously registered javascript function called before the rendering.
  23845. * This function is passed the current mesh.
  23846. * Returns the Mesh.
  23847. */
  23848. Mesh.prototype.unregisterBeforeRender = function (func) {
  23849. this.onBeforeRenderObservable.removeCallback(func);
  23850. return this;
  23851. };
  23852. /**
  23853. * Registers for this mesh a javascript function called just after the rendering is complete.
  23854. * This function is passed the current mesh.
  23855. * Returns the Mesh.
  23856. */
  23857. Mesh.prototype.registerAfterRender = function (func) {
  23858. this.onAfterRenderObservable.add(func);
  23859. return this;
  23860. };
  23861. /**
  23862. * Disposes a previously registered javascript function called after the rendering.
  23863. * This function is passed the current mesh.
  23864. * Return the Mesh.
  23865. */
  23866. Mesh.prototype.unregisterAfterRender = function (func) {
  23867. this.onAfterRenderObservable.removeCallback(func);
  23868. return this;
  23869. };
  23870. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  23871. var scene = this.getScene();
  23872. this._batchCache.mustReturn = false;
  23873. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  23874. this._batchCache.visibleInstances[subMeshId] = null;
  23875. if (this._visibleInstances) {
  23876. var currentRenderId = scene.getRenderId();
  23877. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  23878. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  23879. var selfRenderId = this._renderId;
  23880. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  23881. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  23882. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  23883. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  23884. }
  23885. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  23886. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  23887. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  23888. this._batchCache.mustReturn = true;
  23889. return this._batchCache;
  23890. }
  23891. if (currentRenderId !== selfRenderId) {
  23892. this._batchCache.renderSelf[subMeshId] = false;
  23893. }
  23894. }
  23895. this._renderIdForInstances[subMeshId] = currentRenderId;
  23896. }
  23897. return this._batchCache;
  23898. };
  23899. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  23900. var visibleInstances = batch.visibleInstances[subMesh._id];
  23901. if (!visibleInstances) {
  23902. return this;
  23903. }
  23904. var matricesCount = visibleInstances.length + 1;
  23905. var bufferSize = matricesCount * 16 * 4;
  23906. var currentInstancesBufferSize = this._instancesBufferSize;
  23907. var instancesBuffer = this._instancesBuffer;
  23908. while (this._instancesBufferSize < bufferSize) {
  23909. this._instancesBufferSize *= 2;
  23910. }
  23911. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  23912. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  23913. }
  23914. var offset = 0;
  23915. var instancesCount = 0;
  23916. var world = this.getWorldMatrix();
  23917. if (batch.renderSelf[subMesh._id]) {
  23918. world.copyToArray(this._instancesData, offset);
  23919. offset += 16;
  23920. instancesCount++;
  23921. }
  23922. if (visibleInstances) {
  23923. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  23924. var instance = visibleInstances[instanceIndex];
  23925. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  23926. offset += 16;
  23927. instancesCount++;
  23928. }
  23929. }
  23930. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  23931. if (instancesBuffer) {
  23932. instancesBuffer.dispose();
  23933. }
  23934. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  23935. this._instancesBuffer = instancesBuffer;
  23936. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  23937. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  23938. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  23939. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  23940. }
  23941. else {
  23942. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  23943. }
  23944. this._bind(subMesh, effect, fillMode);
  23945. this._draw(subMesh, fillMode, instancesCount);
  23946. engine.unbindInstanceAttributes();
  23947. return this;
  23948. };
  23949. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  23950. var scene = this.getScene();
  23951. var engine = scene.getEngine();
  23952. if (hardwareInstancedRendering) {
  23953. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  23954. }
  23955. else {
  23956. if (batch.renderSelf[subMesh._id]) {
  23957. // Draw
  23958. if (onBeforeDraw) {
  23959. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  23960. }
  23961. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  23962. }
  23963. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  23964. if (visibleInstancesForSubMesh) {
  23965. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  23966. var instance = visibleInstancesForSubMesh[instanceIndex];
  23967. // World
  23968. var world = instance.getWorldMatrix();
  23969. if (onBeforeDraw) {
  23970. onBeforeDraw(true, world, effectiveMaterial);
  23971. }
  23972. // Draw
  23973. this._draw(subMesh, fillMode);
  23974. }
  23975. }
  23976. }
  23977. return this;
  23978. };
  23979. /**
  23980. * Triggers the draw call for the mesh.
  23981. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  23982. * Returns the Mesh.
  23983. */
  23984. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  23985. this.checkOcclusionQuery();
  23986. if (this._isOccluded) {
  23987. return this;
  23988. }
  23989. var scene = this.getScene();
  23990. // Managing instances
  23991. var batch = this._getInstancesRenderList(subMesh._id);
  23992. if (batch.mustReturn) {
  23993. return this;
  23994. }
  23995. // Checking geometry state
  23996. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23997. return this;
  23998. }
  23999. this.onBeforeRenderObservable.notifyObservers(this);
  24000. var engine = scene.getEngine();
  24001. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  24002. // Material
  24003. var material = subMesh.getMaterial();
  24004. if (!material) {
  24005. return this;
  24006. }
  24007. this._effectiveMaterial = material;
  24008. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24009. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  24010. return this;
  24011. }
  24012. }
  24013. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  24014. return this;
  24015. }
  24016. // Alpha mode
  24017. if (enableAlphaMode) {
  24018. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  24019. }
  24020. // Outline - step 1
  24021. var savedDepthWrite = engine.getDepthWrite();
  24022. if (this.renderOutline) {
  24023. engine.setDepthWrite(false);
  24024. scene.getOutlineRenderer().render(subMesh, batch);
  24025. engine.setDepthWrite(savedDepthWrite);
  24026. }
  24027. var effect;
  24028. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24029. effect = subMesh.effect;
  24030. }
  24031. else {
  24032. effect = this._effectiveMaterial.getEffect();
  24033. }
  24034. if (!effect) {
  24035. return this;
  24036. }
  24037. var reverse = this._effectiveMaterial._preBind(effect, this.overrideMaterialSideOrientation);
  24038. if (this._effectiveMaterial.forceDepthWrite) {
  24039. engine.setDepthWrite(true);
  24040. }
  24041. // Bind
  24042. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  24043. if (!hardwareInstancedRendering) {
  24044. this._bind(subMesh, effect, fillMode);
  24045. }
  24046. var world = this.getWorldMatrix();
  24047. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24048. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  24049. }
  24050. else {
  24051. this._effectiveMaterial.bind(world, this);
  24052. }
  24053. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  24054. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  24055. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  24056. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  24057. }
  24058. // Draw
  24059. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  24060. // Unbind
  24061. this._effectiveMaterial.unbind();
  24062. // Outline - step 2
  24063. if (this.renderOutline && savedDepthWrite) {
  24064. engine.setDepthWrite(true);
  24065. engine.setColorWrite(false);
  24066. scene.getOutlineRenderer().render(subMesh, batch);
  24067. engine.setColorWrite(true);
  24068. }
  24069. // Overlay
  24070. if (this.renderOverlay) {
  24071. var currentMode = engine.getAlphaMode();
  24072. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  24073. scene.getOutlineRenderer().render(subMesh, batch, true);
  24074. engine.setAlphaMode(currentMode);
  24075. }
  24076. this.onAfterRenderObservable.notifyObservers(this);
  24077. return this;
  24078. };
  24079. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  24080. if (isInstance) {
  24081. effectiveMaterial.bindOnlyWorldMatrix(world);
  24082. }
  24083. return this;
  24084. };
  24085. /**
  24086. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  24087. */
  24088. Mesh.prototype.getEmittedParticleSystems = function () {
  24089. var results = new Array();
  24090. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  24091. var particleSystem = this.getScene().particleSystems[index];
  24092. if (particleSystem.emitter === this) {
  24093. results.push(particleSystem);
  24094. }
  24095. }
  24096. return results;
  24097. };
  24098. /**
  24099. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  24100. */
  24101. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  24102. var results = new Array();
  24103. var descendants = this.getDescendants();
  24104. descendants.push(this);
  24105. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  24106. var particleSystem = this.getScene().particleSystems[index];
  24107. var emitter = particleSystem.emitter;
  24108. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  24109. results.push(particleSystem);
  24110. }
  24111. }
  24112. return results;
  24113. };
  24114. Mesh.prototype._checkDelayState = function () {
  24115. var scene = this.getScene();
  24116. if (this._geometry) {
  24117. this._geometry.load(scene);
  24118. }
  24119. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24120. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  24121. this._queueLoad(this, scene);
  24122. }
  24123. return this;
  24124. };
  24125. Mesh.prototype._queueLoad = function (mesh, scene) {
  24126. var _this = this;
  24127. scene._addPendingData(mesh);
  24128. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  24129. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  24130. if (data instanceof ArrayBuffer) {
  24131. _this._delayLoadingFunction(data, _this);
  24132. }
  24133. else {
  24134. _this._delayLoadingFunction(JSON.parse(data), _this);
  24135. }
  24136. _this.instances.forEach(function (instance) {
  24137. instance._syncSubMeshes();
  24138. });
  24139. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24140. scene._removePendingData(_this);
  24141. }, function () { }, scene.database, getBinaryData);
  24142. return this;
  24143. };
  24144. /**
  24145. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  24146. */
  24147. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  24148. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24149. return false;
  24150. }
  24151. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  24152. return false;
  24153. }
  24154. this._checkDelayState();
  24155. return true;
  24156. };
  24157. /**
  24158. * Sets the mesh material by the material or multiMaterial `id` property.
  24159. * The material `id` is a string identifying the material or the multiMaterial.
  24160. * This method returns the Mesh.
  24161. */
  24162. Mesh.prototype.setMaterialByID = function (id) {
  24163. var materials = this.getScene().materials;
  24164. var index;
  24165. for (index = materials.length - 1; index > -1; index--) {
  24166. if (materials[index].id === id) {
  24167. this.material = materials[index];
  24168. return this;
  24169. }
  24170. }
  24171. // Multi
  24172. var multiMaterials = this.getScene().multiMaterials;
  24173. for (index = multiMaterials.length - 1; index > -1; index--) {
  24174. if (multiMaterials[index].id === id) {
  24175. this.material = multiMaterials[index];
  24176. return this;
  24177. }
  24178. }
  24179. return this;
  24180. };
  24181. /**
  24182. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  24183. */
  24184. Mesh.prototype.getAnimatables = function () {
  24185. var results = new Array();
  24186. if (this.material) {
  24187. results.push(this.material);
  24188. }
  24189. if (this.skeleton) {
  24190. results.push(this.skeleton);
  24191. }
  24192. return results;
  24193. };
  24194. /**
  24195. * Modifies the mesh geometry according to the passed transformation matrix.
  24196. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  24197. * The mesh normals are modified accordingly the same transformation.
  24198. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  24199. * Note that, under the hood, this method sets a new VertexBuffer each call.
  24200. * Returns the Mesh.
  24201. */
  24202. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  24203. // Position
  24204. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24205. return this;
  24206. }
  24207. var submeshes = this.subMeshes.splice(0);
  24208. this._resetPointsArrayCache();
  24209. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24210. var temp = new Array();
  24211. var index;
  24212. for (index = 0; index < data.length; index += 3) {
  24213. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  24214. }
  24215. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  24216. // Normals
  24217. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24218. return this;
  24219. }
  24220. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24221. temp = [];
  24222. for (index = 0; index < data.length; index += 3) {
  24223. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  24224. }
  24225. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  24226. // flip faces?
  24227. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  24228. this.flipFaces();
  24229. }
  24230. // Restore submeshes
  24231. this.releaseSubMeshes();
  24232. this.subMeshes = submeshes;
  24233. return this;
  24234. };
  24235. /**
  24236. * Modifies the mesh geometry according to its own current World Matrix.
  24237. * The mesh World Matrix is then reset.
  24238. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  24239. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  24240. * Note that, under the hood, this method sets a new VertexBuffer each call.
  24241. * Returns the Mesh.
  24242. */
  24243. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  24244. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  24245. this.scaling.copyFromFloats(1, 1, 1);
  24246. this.position.copyFromFloats(0, 0, 0);
  24247. this.rotation.copyFromFloats(0, 0, 0);
  24248. //only if quaternion is already set
  24249. if (this.rotationQuaternion) {
  24250. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  24251. }
  24252. this._worldMatrix = BABYLON.Matrix.Identity();
  24253. return this;
  24254. };
  24255. Object.defineProperty(Mesh.prototype, "_positions", {
  24256. // Cache
  24257. get: function () {
  24258. if (this._geometry) {
  24259. return this._geometry._positions;
  24260. }
  24261. return null;
  24262. },
  24263. enumerable: true,
  24264. configurable: true
  24265. });
  24266. Mesh.prototype._resetPointsArrayCache = function () {
  24267. if (this._geometry) {
  24268. this._geometry._resetPointsArrayCache();
  24269. }
  24270. return this;
  24271. };
  24272. Mesh.prototype._generatePointsArray = function () {
  24273. if (this._geometry) {
  24274. return this._geometry._generatePointsArray();
  24275. }
  24276. return false;
  24277. };
  24278. /**
  24279. * Returns a new Mesh object generated from the current mesh properties.
  24280. * This method must not get confused with createInstance().
  24281. * The parameter `name` is a string, the name given to the new mesh.
  24282. * The optional parameter `newParent` can be any Node object (default `null`).
  24283. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  24284. * 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.
  24285. */
  24286. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  24287. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  24288. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  24289. };
  24290. /**
  24291. * Disposes the Mesh.
  24292. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  24293. * Returns nothing.
  24294. */
  24295. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  24296. var _this = this;
  24297. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  24298. this.morphTargetManager = null;
  24299. if (this._geometry) {
  24300. this._geometry.releaseForMesh(this, true);
  24301. }
  24302. // Sources
  24303. var meshes = this.getScene().meshes;
  24304. meshes.forEach(function (mesh) {
  24305. if (mesh._source && mesh._source === _this) {
  24306. mesh._source = null;
  24307. }
  24308. });
  24309. this._source = null;
  24310. // Instances
  24311. if (this._instancesBuffer) {
  24312. this._instancesBuffer.dispose();
  24313. this._instancesBuffer = null;
  24314. }
  24315. while (this.instances.length) {
  24316. this.instances[0].dispose();
  24317. }
  24318. // Highlight layers.
  24319. var highlightLayers = this.getScene().highlightLayers;
  24320. for (var i = 0; i < highlightLayers.length; i++) {
  24321. var highlightLayer = highlightLayers[i];
  24322. if (highlightLayer) {
  24323. highlightLayer.removeMesh(this);
  24324. highlightLayer.removeExcludedMesh(this);
  24325. }
  24326. }
  24327. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  24328. };
  24329. /**
  24330. * Modifies the mesh geometry according to a displacement map.
  24331. * 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.
  24332. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24333. * This method returns nothing.
  24334. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  24335. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24336. * 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.
  24337. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24338. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24339. *
  24340. * Returns the Mesh.
  24341. */
  24342. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  24343. var _this = this;
  24344. var scene = this.getScene();
  24345. var onload = function (img) {
  24346. // Getting height map data
  24347. var canvas = document.createElement("canvas");
  24348. var context = canvas.getContext("2d");
  24349. var heightMapWidth = img.width;
  24350. var heightMapHeight = img.height;
  24351. canvas.width = heightMapWidth;
  24352. canvas.height = heightMapHeight;
  24353. context.drawImage(img, 0, 0);
  24354. // Create VertexData from map data
  24355. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  24356. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  24357. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  24358. //execute success callback, if set
  24359. if (onSuccess) {
  24360. onSuccess(_this);
  24361. }
  24362. };
  24363. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  24364. return this;
  24365. };
  24366. /**
  24367. * Modifies the mesh geometry according to a displacementMap buffer.
  24368. * 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.
  24369. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24370. * This method returns nothing.
  24371. * 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.
  24372. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  24373. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24374. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24375. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24376. *
  24377. * Returns the Mesh.
  24378. */
  24379. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  24380. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  24381. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  24382. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24383. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  24384. return this;
  24385. }
  24386. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24387. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24388. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24389. var position = BABYLON.Vector3.Zero();
  24390. var normal = BABYLON.Vector3.Zero();
  24391. var uv = BABYLON.Vector2.Zero();
  24392. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  24393. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  24394. for (var index = 0; index < positions.length; index += 3) {
  24395. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  24396. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  24397. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  24398. // Compute height
  24399. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  24400. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  24401. var pos = (u + v * heightMapWidth) * 4;
  24402. var r = buffer[pos] / 255.0;
  24403. var g = buffer[pos + 1] / 255.0;
  24404. var b = buffer[pos + 2] / 255.0;
  24405. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24406. normal.normalize();
  24407. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  24408. position = position.add(normal);
  24409. position.toArray(positions, index);
  24410. }
  24411. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  24412. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  24413. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  24414. return this;
  24415. };
  24416. /**
  24417. * Modify the mesh to get a flat shading rendering.
  24418. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  24419. * This method returns the Mesh.
  24420. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  24421. */
  24422. Mesh.prototype.convertToFlatShadedMesh = function () {
  24423. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  24424. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24425. var kinds = this.getVerticesDataKinds();
  24426. var vbs = {};
  24427. var data = {};
  24428. var newdata = {};
  24429. var updatableNormals = false;
  24430. var kindIndex;
  24431. var kind;
  24432. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24433. kind = kinds[kindIndex];
  24434. var vertexBuffer = this.getVertexBuffer(kind);
  24435. if (kind === BABYLON.VertexBuffer.NormalKind) {
  24436. updatableNormals = vertexBuffer.isUpdatable();
  24437. kinds.splice(kindIndex, 1);
  24438. kindIndex--;
  24439. continue;
  24440. }
  24441. vbs[kind] = vertexBuffer;
  24442. data[kind] = vbs[kind].getData();
  24443. newdata[kind] = [];
  24444. }
  24445. // Save previous submeshes
  24446. var previousSubmeshes = this.subMeshes.slice(0);
  24447. var indices = this.getIndices();
  24448. var totalIndices = this.getTotalIndices();
  24449. // Generating unique vertices per face
  24450. var index;
  24451. for (index = 0; index < totalIndices; index++) {
  24452. var vertexIndex = indices[index];
  24453. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24454. kind = kinds[kindIndex];
  24455. var stride = vbs[kind].getStrideSize();
  24456. for (var offset = 0; offset < stride; offset++) {
  24457. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24458. }
  24459. }
  24460. }
  24461. // Updating faces & normal
  24462. var normals = [];
  24463. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  24464. for (index = 0; index < totalIndices; index += 3) {
  24465. indices[index] = index;
  24466. indices[index + 1] = index + 1;
  24467. indices[index + 2] = index + 2;
  24468. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  24469. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  24470. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  24471. var p1p2 = p1.subtract(p2);
  24472. var p3p2 = p3.subtract(p2);
  24473. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  24474. // Store same normals for every vertex
  24475. for (var localIndex = 0; localIndex < 3; localIndex++) {
  24476. normals.push(normal.x);
  24477. normals.push(normal.y);
  24478. normals.push(normal.z);
  24479. }
  24480. }
  24481. this.setIndices(indices);
  24482. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  24483. // Updating vertex buffers
  24484. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24485. kind = kinds[kindIndex];
  24486. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24487. }
  24488. // Updating submeshes
  24489. this.releaseSubMeshes();
  24490. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24491. var previousOne = previousSubmeshes[submeshIndex];
  24492. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24493. }
  24494. this.synchronizeInstances();
  24495. return this;
  24496. };
  24497. /**
  24498. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  24499. * In other words, more vertices, no more indices and a single bigger VBO.
  24500. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  24501. * Returns the Mesh.
  24502. */
  24503. Mesh.prototype.convertToUnIndexedMesh = function () {
  24504. /// <summary>Remove indices by unfolding faces into buffers</summary>
  24505. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24506. var kinds = this.getVerticesDataKinds();
  24507. var vbs = {};
  24508. var data = {};
  24509. var newdata = {};
  24510. var kindIndex;
  24511. var kind;
  24512. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24513. kind = kinds[kindIndex];
  24514. var vertexBuffer = this.getVertexBuffer(kind);
  24515. vbs[kind] = vertexBuffer;
  24516. data[kind] = vbs[kind].getData();
  24517. newdata[kind] = [];
  24518. }
  24519. // Save previous submeshes
  24520. var previousSubmeshes = this.subMeshes.slice(0);
  24521. var indices = this.getIndices();
  24522. var totalIndices = this.getTotalIndices();
  24523. // Generating unique vertices per face
  24524. var index;
  24525. for (index = 0; index < totalIndices; index++) {
  24526. var vertexIndex = indices[index];
  24527. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24528. kind = kinds[kindIndex];
  24529. var stride = vbs[kind].getStrideSize();
  24530. for (var offset = 0; offset < stride; offset++) {
  24531. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24532. }
  24533. }
  24534. }
  24535. // Updating indices
  24536. for (index = 0; index < totalIndices; index += 3) {
  24537. indices[index] = index;
  24538. indices[index + 1] = index + 1;
  24539. indices[index + 2] = index + 2;
  24540. }
  24541. this.setIndices(indices);
  24542. // Updating vertex buffers
  24543. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24544. kind = kinds[kindIndex];
  24545. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24546. }
  24547. // Updating submeshes
  24548. this.releaseSubMeshes();
  24549. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24550. var previousOne = previousSubmeshes[submeshIndex];
  24551. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24552. }
  24553. this._unIndexed = true;
  24554. this.synchronizeInstances();
  24555. return this;
  24556. };
  24557. /**
  24558. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  24559. * This method returns the Mesh.
  24560. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  24561. */
  24562. Mesh.prototype.flipFaces = function (flipNormals) {
  24563. if (flipNormals === void 0) { flipNormals = false; }
  24564. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  24565. var i;
  24566. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  24567. for (i = 0; i < vertex_data.normals.length; i++) {
  24568. vertex_data.normals[i] *= -1;
  24569. }
  24570. }
  24571. if (vertex_data.indices) {
  24572. var temp;
  24573. for (i = 0; i < vertex_data.indices.length; i += 3) {
  24574. // reassign indices
  24575. temp = vertex_data.indices[i + 1];
  24576. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  24577. vertex_data.indices[i + 2] = temp;
  24578. }
  24579. }
  24580. vertex_data.applyToMesh(this);
  24581. return this;
  24582. };
  24583. // Instances
  24584. /**
  24585. * Creates a new InstancedMesh object from the mesh model.
  24586. * An instance shares the same properties and the same material than its model.
  24587. * Only these properties of each instance can then be set individually :
  24588. * - position
  24589. * - rotation
  24590. * - rotationQuaternion
  24591. * - setPivotMatrix
  24592. * - scaling
  24593. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  24594. * Warning : this method is not supported for Line mesh and LineSystem
  24595. */
  24596. Mesh.prototype.createInstance = function (name) {
  24597. return new BABYLON.InstancedMesh(name, this);
  24598. };
  24599. /**
  24600. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  24601. * After this call, all the mesh instances have the same submeshes than the current mesh.
  24602. * This method returns the Mesh.
  24603. */
  24604. Mesh.prototype.synchronizeInstances = function () {
  24605. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  24606. var instance = this.instances[instanceIndex];
  24607. instance._syncSubMeshes();
  24608. }
  24609. return this;
  24610. };
  24611. /**
  24612. * Simplify the mesh according to the given array of settings.
  24613. * Function will return immediately and will simplify async. It returns the Mesh.
  24614. * @param settings a collection of simplification settings.
  24615. * @param parallelProcessing should all levels calculate parallel or one after the other.
  24616. * @param type the type of simplification to run.
  24617. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  24618. */
  24619. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  24620. if (parallelProcessing === void 0) { parallelProcessing = true; }
  24621. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  24622. this.getScene().simplificationQueue.addTask({
  24623. settings: settings,
  24624. parallelProcessing: parallelProcessing,
  24625. mesh: this,
  24626. simplificationType: simplificationType,
  24627. successCallback: successCallback
  24628. });
  24629. return this;
  24630. };
  24631. /**
  24632. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  24633. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  24634. * This should be used together with the simplification to avoid disappearing triangles.
  24635. * Returns the Mesh.
  24636. * @param successCallback an optional success callback to be called after the optimization finished.
  24637. */
  24638. Mesh.prototype.optimizeIndices = function (successCallback) {
  24639. var _this = this;
  24640. var indices = this.getIndices();
  24641. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24642. if (!positions || !indices) {
  24643. return this;
  24644. }
  24645. var vectorPositions = new Array();
  24646. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  24647. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  24648. }
  24649. var dupes = new Array();
  24650. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  24651. var realPos = vectorPositions.length - 1 - iteration;
  24652. var testedPosition = vectorPositions[realPos];
  24653. for (var j = 0; j < realPos; ++j) {
  24654. var againstPosition = vectorPositions[j];
  24655. if (testedPosition.equals(againstPosition)) {
  24656. dupes[realPos] = j;
  24657. break;
  24658. }
  24659. }
  24660. }, function () {
  24661. for (var i = 0; i < indices.length; ++i) {
  24662. indices[i] = dupes[indices[i]] || indices[i];
  24663. }
  24664. //indices are now reordered
  24665. var originalSubMeshes = _this.subMeshes.slice(0);
  24666. _this.setIndices(indices);
  24667. _this.subMeshes = originalSubMeshes;
  24668. if (successCallback) {
  24669. successCallback(_this);
  24670. }
  24671. });
  24672. return this;
  24673. };
  24674. Mesh.prototype.serialize = function (serializationObject) {
  24675. serializationObject.name = this.name;
  24676. serializationObject.id = this.id;
  24677. serializationObject.type = this.getClassName();
  24678. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  24679. serializationObject.tags = BABYLON.Tags.GetTags(this);
  24680. }
  24681. serializationObject.position = this.position.asArray();
  24682. if (this.rotationQuaternion) {
  24683. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  24684. }
  24685. else if (this.rotation) {
  24686. serializationObject.rotation = this.rotation.asArray();
  24687. }
  24688. serializationObject.scaling = this.scaling.asArray();
  24689. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  24690. serializationObject.isEnabled = this.isEnabled();
  24691. serializationObject.isVisible = this.isVisible;
  24692. serializationObject.infiniteDistance = this.infiniteDistance;
  24693. serializationObject.pickable = this.isPickable;
  24694. serializationObject.receiveShadows = this.receiveShadows;
  24695. serializationObject.billboardMode = this.billboardMode;
  24696. serializationObject.visibility = this.visibility;
  24697. serializationObject.checkCollisions = this.checkCollisions;
  24698. serializationObject.isBlocker = this.isBlocker;
  24699. // Parent
  24700. if (this.parent) {
  24701. serializationObject.parentId = this.parent.id;
  24702. }
  24703. // Geometry
  24704. var geometry = this._geometry;
  24705. if (geometry) {
  24706. var geometryId = geometry.id;
  24707. serializationObject.geometryId = geometryId;
  24708. // SubMeshes
  24709. serializationObject.subMeshes = [];
  24710. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  24711. var subMesh = this.subMeshes[subIndex];
  24712. serializationObject.subMeshes.push({
  24713. materialIndex: subMesh.materialIndex,
  24714. verticesStart: subMesh.verticesStart,
  24715. verticesCount: subMesh.verticesCount,
  24716. indexStart: subMesh.indexStart,
  24717. indexCount: subMesh.indexCount
  24718. });
  24719. }
  24720. }
  24721. // Material
  24722. if (this.material) {
  24723. serializationObject.materialId = this.material.id;
  24724. }
  24725. else {
  24726. this.material = null;
  24727. }
  24728. // Morph targets
  24729. if (this.morphTargetManager) {
  24730. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  24731. }
  24732. // Skeleton
  24733. if (this.skeleton) {
  24734. serializationObject.skeletonId = this.skeleton.id;
  24735. }
  24736. // Physics
  24737. //TODO implement correct serialization for physics impostors.
  24738. var impostor = this.getPhysicsImpostor();
  24739. if (impostor) {
  24740. serializationObject.physicsMass = impostor.getParam("mass");
  24741. serializationObject.physicsFriction = impostor.getParam("friction");
  24742. serializationObject.physicsRestitution = impostor.getParam("mass");
  24743. serializationObject.physicsImpostor = impostor.type;
  24744. }
  24745. // Metadata
  24746. if (this.metadata) {
  24747. serializationObject.metadata = this.metadata;
  24748. }
  24749. // Instances
  24750. serializationObject.instances = [];
  24751. for (var index = 0; index < this.instances.length; index++) {
  24752. var instance = this.instances[index];
  24753. var serializationInstance = {
  24754. name: instance.name,
  24755. position: instance.position.asArray(),
  24756. scaling: instance.scaling.asArray()
  24757. };
  24758. if (instance.rotationQuaternion) {
  24759. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  24760. }
  24761. else if (instance.rotation) {
  24762. serializationInstance.rotation = instance.rotation.asArray();
  24763. }
  24764. serializationObject.instances.push(serializationInstance);
  24765. // Animations
  24766. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  24767. serializationInstance.ranges = instance.serializeAnimationRanges();
  24768. }
  24769. //
  24770. // Animations
  24771. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24772. serializationObject.ranges = this.serializeAnimationRanges();
  24773. // Layer mask
  24774. serializationObject.layerMask = this.layerMask;
  24775. // Alpha
  24776. serializationObject.alphaIndex = this.alphaIndex;
  24777. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  24778. // Overlay
  24779. serializationObject.overlayAlpha = this.overlayAlpha;
  24780. serializationObject.overlayColor = this.overlayColor.asArray();
  24781. serializationObject.renderOverlay = this.renderOverlay;
  24782. // Fog
  24783. serializationObject.applyFog = this.applyFog;
  24784. // Action Manager
  24785. if (this.actionManager) {
  24786. serializationObject.actions = this.actionManager.serialize(this.name);
  24787. }
  24788. };
  24789. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  24790. if (!this.geometry) {
  24791. return;
  24792. }
  24793. this._markSubMeshesAsAttributesDirty();
  24794. var morphTargetManager = this._morphTargetManager;
  24795. if (morphTargetManager && morphTargetManager.vertexCount) {
  24796. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  24797. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  24798. this.morphTargetManager = null;
  24799. return;
  24800. }
  24801. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  24802. var morphTarget = morphTargetManager.getActiveTarget(index);
  24803. var positions = morphTarget.getPositions();
  24804. if (!positions) {
  24805. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  24806. return;
  24807. }
  24808. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  24809. var normals = morphTarget.getNormals();
  24810. if (normals) {
  24811. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  24812. }
  24813. var tangents = morphTarget.getTangents();
  24814. if (tangents) {
  24815. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  24816. }
  24817. }
  24818. }
  24819. else {
  24820. var index = 0;
  24821. // Positions
  24822. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  24823. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  24824. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  24825. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  24826. }
  24827. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  24828. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  24829. }
  24830. index++;
  24831. }
  24832. }
  24833. };
  24834. // Statics
  24835. /**
  24836. * Returns a new Mesh object parsed from the source provided.
  24837. * The parameter `parsedMesh` is the source.
  24838. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  24839. */
  24840. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  24841. var mesh;
  24842. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  24843. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  24844. }
  24845. else {
  24846. mesh = new Mesh(parsedMesh.name, scene);
  24847. }
  24848. mesh.id = parsedMesh.id;
  24849. if (BABYLON.Tags) {
  24850. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  24851. }
  24852. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  24853. if (parsedMesh.metadata !== undefined) {
  24854. mesh.metadata = parsedMesh.metadata;
  24855. }
  24856. if (parsedMesh.rotationQuaternion) {
  24857. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  24858. }
  24859. else if (parsedMesh.rotation) {
  24860. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  24861. }
  24862. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  24863. if (parsedMesh.localMatrix) {
  24864. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  24865. }
  24866. else if (parsedMesh.pivotMatrix) {
  24867. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  24868. }
  24869. mesh.setEnabled(parsedMesh.isEnabled);
  24870. mesh.isVisible = parsedMesh.isVisible;
  24871. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  24872. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  24873. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  24874. if (parsedMesh.applyFog !== undefined) {
  24875. mesh.applyFog = parsedMesh.applyFog;
  24876. }
  24877. if (parsedMesh.pickable !== undefined) {
  24878. mesh.isPickable = parsedMesh.pickable;
  24879. }
  24880. if (parsedMesh.alphaIndex !== undefined) {
  24881. mesh.alphaIndex = parsedMesh.alphaIndex;
  24882. }
  24883. mesh.receiveShadows = parsedMesh.receiveShadows;
  24884. mesh.billboardMode = parsedMesh.billboardMode;
  24885. if (parsedMesh.visibility !== undefined) {
  24886. mesh.visibility = parsedMesh.visibility;
  24887. }
  24888. mesh.checkCollisions = parsedMesh.checkCollisions;
  24889. if (parsedMesh.isBlocker !== undefined) {
  24890. mesh.isBlocker = parsedMesh.isBlocker;
  24891. }
  24892. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  24893. // freezeWorldMatrix
  24894. if (parsedMesh.freezeWorldMatrix) {
  24895. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  24896. }
  24897. // Parent
  24898. if (parsedMesh.parentId) {
  24899. mesh._waitingParentId = parsedMesh.parentId;
  24900. }
  24901. // Actions
  24902. if (parsedMesh.actions !== undefined) {
  24903. mesh._waitingActions = parsedMesh.actions;
  24904. }
  24905. // Overlay
  24906. if (parsedMesh.overlayAlpha !== undefined) {
  24907. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  24908. }
  24909. if (parsedMesh.overlayColor !== undefined) {
  24910. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  24911. }
  24912. if (parsedMesh.renderOverlay !== undefined) {
  24913. mesh.renderOverlay = parsedMesh.renderOverlay;
  24914. }
  24915. // Geometry
  24916. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  24917. if (parsedMesh.delayLoadingFile) {
  24918. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24919. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  24920. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  24921. if (parsedMesh._binaryInfo) {
  24922. mesh._binaryInfo = parsedMesh._binaryInfo;
  24923. }
  24924. mesh._delayInfo = [];
  24925. if (parsedMesh.hasUVs) {
  24926. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  24927. }
  24928. if (parsedMesh.hasUVs2) {
  24929. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  24930. }
  24931. if (parsedMesh.hasUVs3) {
  24932. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  24933. }
  24934. if (parsedMesh.hasUVs4) {
  24935. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  24936. }
  24937. if (parsedMesh.hasUVs5) {
  24938. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  24939. }
  24940. if (parsedMesh.hasUVs6) {
  24941. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  24942. }
  24943. if (parsedMesh.hasColors) {
  24944. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  24945. }
  24946. if (parsedMesh.hasMatricesIndices) {
  24947. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24948. }
  24949. if (parsedMesh.hasMatricesWeights) {
  24950. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24951. }
  24952. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  24953. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  24954. mesh._checkDelayState();
  24955. }
  24956. }
  24957. else {
  24958. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  24959. }
  24960. // Material
  24961. if (parsedMesh.materialId) {
  24962. mesh.setMaterialByID(parsedMesh.materialId);
  24963. }
  24964. else {
  24965. mesh.material = null;
  24966. }
  24967. // Morph targets
  24968. if (parsedMesh.morphTargetManagerId > -1) {
  24969. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  24970. }
  24971. // Skeleton
  24972. if (parsedMesh.skeletonId > -1) {
  24973. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  24974. if (parsedMesh.numBoneInfluencers) {
  24975. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  24976. }
  24977. }
  24978. // Animations
  24979. if (parsedMesh.animations) {
  24980. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24981. var parsedAnimation = parsedMesh.animations[animationIndex];
  24982. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24983. }
  24984. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  24985. }
  24986. if (parsedMesh.autoAnimate) {
  24987. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  24988. }
  24989. // Layer Mask
  24990. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  24991. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  24992. }
  24993. else {
  24994. mesh.layerMask = 0x0FFFFFFF;
  24995. }
  24996. // Physics
  24997. if (parsedMesh.physicsImpostor) {
  24998. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  24999. mass: parsedMesh.physicsMass,
  25000. friction: parsedMesh.physicsFriction,
  25001. restitution: parsedMesh.physicsRestitution
  25002. }, scene);
  25003. }
  25004. // Instances
  25005. if (parsedMesh.instances) {
  25006. for (var index = 0; index < parsedMesh.instances.length; index++) {
  25007. var parsedInstance = parsedMesh.instances[index];
  25008. var instance = mesh.createInstance(parsedInstance.name);
  25009. if (BABYLON.Tags) {
  25010. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  25011. }
  25012. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  25013. if (parsedInstance.parentId) {
  25014. instance._waitingParentId = parsedInstance.parentId;
  25015. }
  25016. if (parsedInstance.rotationQuaternion) {
  25017. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  25018. }
  25019. else if (parsedInstance.rotation) {
  25020. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  25021. }
  25022. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  25023. instance.checkCollisions = mesh.checkCollisions;
  25024. if (parsedMesh.animations) {
  25025. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  25026. parsedAnimation = parsedMesh.animations[animationIndex];
  25027. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25028. }
  25029. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  25030. }
  25031. }
  25032. }
  25033. return mesh;
  25034. };
  25035. /**
  25036. * Creates a ribbon mesh.
  25037. * Please consider using the same method from the MeshBuilder class instead.
  25038. * 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.
  25039. *
  25040. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  25041. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  25042. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  25043. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  25044. * 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.
  25045. * 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.
  25046. * 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
  25047. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25048. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25049. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25050. */
  25051. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  25052. if (closeArray === void 0) { closeArray = false; }
  25053. if (updatable === void 0) { updatable = false; }
  25054. return BABYLON.MeshBuilder.CreateRibbon(name, {
  25055. pathArray: pathArray,
  25056. closeArray: closeArray,
  25057. closePath: closePath,
  25058. offset: offset,
  25059. updatable: updatable,
  25060. sideOrientation: sideOrientation,
  25061. instance: instance
  25062. }, scene);
  25063. };
  25064. /**
  25065. * Creates a plane polygonal mesh. By default, this is a disc.
  25066. * Please consider using the same method from the MeshBuilder class instead.
  25067. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  25068. * 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.
  25069. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25070. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25071. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25072. */
  25073. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  25074. if (scene === void 0) { scene = null; }
  25075. var options = {
  25076. radius: radius,
  25077. tessellation: tessellation,
  25078. sideOrientation: sideOrientation,
  25079. updatable: updatable
  25080. };
  25081. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  25082. };
  25083. /**
  25084. * Creates a box mesh.
  25085. * Please consider using the same method from the MeshBuilder class instead.
  25086. * The parameter `size` sets the size (float) of each box side (default 1).
  25087. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25088. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25089. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25090. */
  25091. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  25092. if (scene === void 0) { scene = null; }
  25093. var options = {
  25094. size: size,
  25095. sideOrientation: sideOrientation,
  25096. updatable: updatable
  25097. };
  25098. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  25099. };
  25100. /**
  25101. * Creates a sphere mesh.
  25102. * Please consider using the same method from the MeshBuilder class instead.
  25103. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  25104. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  25105. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25106. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25107. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25108. */
  25109. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  25110. var options = {
  25111. segments: segments,
  25112. diameterX: diameter,
  25113. diameterY: diameter,
  25114. diameterZ: diameter,
  25115. sideOrientation: sideOrientation,
  25116. updatable: updatable
  25117. };
  25118. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  25119. };
  25120. /**
  25121. * Creates a cylinder or a cone mesh.
  25122. * Please consider using the same method from the MeshBuilder class instead.
  25123. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  25124. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  25125. * 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.
  25126. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  25127. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  25128. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25129. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25130. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25131. */
  25132. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  25133. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  25134. if (scene !== undefined) {
  25135. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  25136. updatable = scene;
  25137. }
  25138. scene = subdivisions;
  25139. subdivisions = 1;
  25140. }
  25141. var options = {
  25142. height: height,
  25143. diameterTop: diameterTop,
  25144. diameterBottom: diameterBottom,
  25145. tessellation: tessellation,
  25146. subdivisions: subdivisions,
  25147. sideOrientation: sideOrientation,
  25148. updatable: updatable
  25149. };
  25150. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  25151. };
  25152. // Torus (Code from SharpDX.org)
  25153. /**
  25154. * Creates a torus mesh.
  25155. * Please consider using the same method from the MeshBuilder class instead.
  25156. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  25157. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  25158. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  25159. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25160. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25161. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25162. */
  25163. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  25164. var options = {
  25165. diameter: diameter,
  25166. thickness: thickness,
  25167. tessellation: tessellation,
  25168. sideOrientation: sideOrientation,
  25169. updatable: updatable
  25170. };
  25171. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  25172. };
  25173. /**
  25174. * Creates a torus knot mesh.
  25175. * Please consider using the same method from the MeshBuilder class instead.
  25176. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  25177. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  25178. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  25179. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  25180. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25181. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25182. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25183. */
  25184. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  25185. var options = {
  25186. radius: radius,
  25187. tube: tube,
  25188. radialSegments: radialSegments,
  25189. tubularSegments: tubularSegments,
  25190. p: p,
  25191. q: q,
  25192. sideOrientation: sideOrientation,
  25193. updatable: updatable
  25194. };
  25195. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  25196. };
  25197. /**
  25198. * Creates a line mesh.
  25199. * Please consider using the same method from the MeshBuilder class instead.
  25200. * 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.
  25201. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25202. * The parameter `points` is an array successive Vector3.
  25203. * 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
  25204. * When updating an instance, remember that only point positions can change, not the number of points.
  25205. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25206. */
  25207. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  25208. if (scene === void 0) { scene = null; }
  25209. if (updatable === void 0) { updatable = false; }
  25210. if (instance === void 0) { instance = null; }
  25211. var options = {
  25212. points: points,
  25213. updatable: updatable,
  25214. instance: instance
  25215. };
  25216. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  25217. };
  25218. /**
  25219. * Creates a dashed line mesh.
  25220. * Please consider using the same method from the MeshBuilder class instead.
  25221. * 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.
  25222. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25223. * The parameter `points` is an array successive Vector3.
  25224. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  25225. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  25226. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  25227. * 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
  25228. * When updating an instance, remember that only point positions can change, not the number of points.
  25229. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25230. */
  25231. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  25232. if (scene === void 0) { scene = null; }
  25233. var options = {
  25234. points: points,
  25235. dashSize: dashSize,
  25236. gapSize: gapSize,
  25237. dashNb: dashNb,
  25238. updatable: updatable,
  25239. instance: instance
  25240. };
  25241. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  25242. };
  25243. /**
  25244. * Creates a polygon mesh.
  25245. * Please consider using the same method from the MeshBuilder class instead.
  25246. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  25247. * 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.
  25248. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25249. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25250. * Remember you can only change the shape positions, not their number when updating a polygon.
  25251. */
  25252. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  25253. var options = {
  25254. shape: shape,
  25255. holes: holes,
  25256. updatable: updatable,
  25257. sideOrientation: sideOrientation
  25258. };
  25259. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  25260. };
  25261. /**
  25262. * Creates an extruded polygon mesh, with depth in the Y direction.
  25263. * Please consider using the same method from the MeshBuilder class instead.
  25264. */
  25265. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  25266. var options = {
  25267. shape: shape,
  25268. holes: holes,
  25269. depth: depth,
  25270. updatable: updatable,
  25271. sideOrientation: sideOrientation
  25272. };
  25273. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  25274. };
  25275. /**
  25276. * Creates an extruded shape mesh.
  25277. * 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.
  25278. * Please consider using the same method from the MeshBuilder class instead.
  25279. *
  25280. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  25281. * 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
  25282. * extruded along the Z axis.
  25283. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  25284. * 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.
  25285. * The parameter `scale` (float, default 1) is the value to scale the shape.
  25286. * 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
  25287. * 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
  25288. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25289. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25290. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25291. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25292. */
  25293. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  25294. if (scene === void 0) { scene = null; }
  25295. var options = {
  25296. shape: shape,
  25297. path: path,
  25298. scale: scale,
  25299. rotation: rotation,
  25300. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  25301. sideOrientation: sideOrientation,
  25302. instance: instance,
  25303. updatable: updatable
  25304. };
  25305. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  25306. };
  25307. /**
  25308. * Creates an custom extruded shape mesh.
  25309. * 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.
  25310. * Please consider using the same method from the MeshBuilder class instead.
  25311. *
  25312. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  25313. * 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
  25314. * extruded along the Z axis.
  25315. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  25316. * 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
  25317. * and the distance of this point from the begining of the path :
  25318. * ```javascript
  25319. * var rotationFunction = function(i, distance) {
  25320. * // do things
  25321. * return rotationValue; }
  25322. * ```
  25323. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  25324. * 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
  25325. * and the distance of this point from the begining of the path :
  25326. * ```javascript
  25327. * var scaleFunction = function(i, distance) {
  25328. * // do things
  25329. * return scaleValue;}
  25330. * ```
  25331. * It must returns a float value that will be the scale value applied to the shape on each path point.
  25332. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  25333. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  25334. * 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
  25335. * 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
  25336. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25337. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25338. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25339. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25340. */
  25341. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  25342. var options = {
  25343. shape: shape,
  25344. path: path,
  25345. scaleFunction: scaleFunction,
  25346. rotationFunction: rotationFunction,
  25347. ribbonCloseArray: ribbonCloseArray,
  25348. ribbonClosePath: ribbonClosePath,
  25349. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  25350. sideOrientation: sideOrientation,
  25351. instance: instance,
  25352. updatable: updatable
  25353. };
  25354. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  25355. };
  25356. /**
  25357. * Creates lathe mesh.
  25358. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  25359. * Please consider using the same method from the MeshBuilder class instead.
  25360. * 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
  25361. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  25362. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  25363. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  25364. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25365. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25366. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25367. */
  25368. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  25369. var options = {
  25370. shape: shape,
  25371. radius: radius,
  25372. tessellation: tessellation,
  25373. sideOrientation: sideOrientation,
  25374. updatable: updatable
  25375. };
  25376. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  25377. };
  25378. /**
  25379. * Creates a plane mesh.
  25380. * Please consider using the same method from the MeshBuilder class instead.
  25381. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  25382. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25383. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25384. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25385. */
  25386. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  25387. var options = {
  25388. size: size,
  25389. width: size,
  25390. height: size,
  25391. sideOrientation: sideOrientation,
  25392. updatable: updatable
  25393. };
  25394. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  25395. };
  25396. /**
  25397. * Creates a ground mesh.
  25398. * Please consider using the same method from the MeshBuilder class instead.
  25399. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  25400. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  25401. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25402. */
  25403. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  25404. var options = {
  25405. width: width,
  25406. height: height,
  25407. subdivisions: subdivisions,
  25408. updatable: updatable
  25409. };
  25410. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  25411. };
  25412. /**
  25413. * Creates a tiled ground mesh.
  25414. * Please consider using the same method from the MeshBuilder class instead.
  25415. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  25416. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  25417. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  25418. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  25419. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  25420. * numbers of subdivisions on the ground width and height of each tile.
  25421. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25422. */
  25423. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  25424. var options = {
  25425. xmin: xmin,
  25426. zmin: zmin,
  25427. xmax: xmax,
  25428. zmax: zmax,
  25429. subdivisions: subdivisions,
  25430. precision: precision,
  25431. updatable: updatable
  25432. };
  25433. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  25434. };
  25435. /**
  25436. * Creates a ground mesh from a height map.
  25437. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  25438. * Please consider using the same method from the MeshBuilder class instead.
  25439. * The parameter `url` sets the URL of the height map image resource.
  25440. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  25441. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  25442. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  25443. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  25444. * 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).
  25445. * This function is passed the newly built mesh :
  25446. * ```javascript
  25447. * function(mesh) { // do things
  25448. * return; }
  25449. * ```
  25450. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25451. */
  25452. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  25453. var options = {
  25454. width: width,
  25455. height: height,
  25456. subdivisions: subdivisions,
  25457. minHeight: minHeight,
  25458. maxHeight: maxHeight,
  25459. updatable: updatable,
  25460. onReady: onReady
  25461. };
  25462. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  25463. };
  25464. /**
  25465. * Creates a tube mesh.
  25466. * 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.
  25467. * Please consider using the same method from the MeshBuilder class instead.
  25468. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  25469. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  25470. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  25471. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  25472. * 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.
  25473. * It must return a radius value (positive float) :
  25474. * ```javascript
  25475. * var radiusFunction = function(i, distance) {
  25476. * // do things
  25477. * return radius; }
  25478. * ```
  25479. * 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
  25480. * 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
  25481. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25482. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25483. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25484. */
  25485. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  25486. var options = {
  25487. path: path,
  25488. radius: radius,
  25489. tessellation: tessellation,
  25490. radiusFunction: radiusFunction,
  25491. arc: 1,
  25492. cap: cap,
  25493. updatable: updatable,
  25494. sideOrientation: sideOrientation,
  25495. instance: instance
  25496. };
  25497. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  25498. };
  25499. /**
  25500. * Creates a polyhedron mesh.
  25501. * Please consider using the same method from the MeshBuilder class instead.
  25502. * 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
  25503. * to choose the wanted type.
  25504. * The parameter `size` (positive float, default 1) sets the polygon size.
  25505. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  25506. * 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`.
  25507. * 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
  25508. * 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)`).
  25509. * 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
  25510. * 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.
  25511. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25512. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25513. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25514. */
  25515. Mesh.CreatePolyhedron = function (name, options, scene) {
  25516. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  25517. };
  25518. /**
  25519. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  25520. * Please consider using the same method from the MeshBuilder class instead.
  25521. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  25522. * 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`).
  25523. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  25524. * 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.
  25525. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25526. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25527. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25528. */
  25529. Mesh.CreateIcoSphere = function (name, options, scene) {
  25530. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  25531. };
  25532. /**
  25533. * Creates a decal mesh.
  25534. * Please consider using the same method from the MeshBuilder class instead.
  25535. * 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.
  25536. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  25537. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  25538. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  25539. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  25540. */
  25541. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  25542. var options = {
  25543. position: position,
  25544. normal: normal,
  25545. size: size,
  25546. angle: angle
  25547. };
  25548. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  25549. };
  25550. // Skeletons
  25551. /**
  25552. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25553. */
  25554. Mesh.prototype.setPositionsForCPUSkinning = function () {
  25555. if (!this._sourcePositions) {
  25556. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25557. if (!source) {
  25558. return this._sourcePositions;
  25559. }
  25560. this._sourcePositions = new Float32Array(source);
  25561. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  25562. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  25563. }
  25564. }
  25565. return this._sourcePositions;
  25566. };
  25567. /**
  25568. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25569. */
  25570. Mesh.prototype.setNormalsForCPUSkinning = function () {
  25571. if (!this._sourceNormals) {
  25572. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25573. if (!source) {
  25574. return this._sourceNormals;
  25575. }
  25576. this._sourceNormals = new Float32Array(source);
  25577. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  25578. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  25579. }
  25580. }
  25581. return this._sourceNormals;
  25582. };
  25583. /**
  25584. * Updates the vertex buffer by applying transformation from the bones.
  25585. * Returns the Mesh.
  25586. *
  25587. * @param {skeleton} skeleton to apply
  25588. */
  25589. Mesh.prototype.applySkeleton = function (skeleton) {
  25590. if (!this.geometry) {
  25591. return this;
  25592. }
  25593. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  25594. return this;
  25595. }
  25596. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  25597. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25598. return this;
  25599. }
  25600. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25601. return this;
  25602. }
  25603. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25604. return this;
  25605. }
  25606. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25607. return this;
  25608. }
  25609. if (!this._sourcePositions) {
  25610. var submeshes = this.subMeshes.slice();
  25611. this.setPositionsForCPUSkinning();
  25612. this.subMeshes = submeshes;
  25613. }
  25614. if (!this._sourceNormals) {
  25615. this.setNormalsForCPUSkinning();
  25616. }
  25617. // positionsData checks for not being Float32Array will only pass at most once
  25618. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25619. if (!positionsData) {
  25620. return this;
  25621. }
  25622. if (!(positionsData instanceof Float32Array)) {
  25623. positionsData = new Float32Array(positionsData);
  25624. }
  25625. // normalsData checks for not being Float32Array will only pass at most once
  25626. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25627. if (!normalsData) {
  25628. return this;
  25629. }
  25630. if (!(normalsData instanceof Float32Array)) {
  25631. normalsData = new Float32Array(normalsData);
  25632. }
  25633. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25634. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25635. if (!matricesWeightsData || !matricesIndicesData) {
  25636. return this;
  25637. }
  25638. var needExtras = this.numBoneInfluencers > 4;
  25639. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25640. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25641. if (!matricesWeightsExtraData || !matricesIndicesExtraData) {
  25642. return this;
  25643. }
  25644. var skeletonMatrices = skeleton.getTransformMatrices(this);
  25645. var tempVector3 = BABYLON.Vector3.Zero();
  25646. var finalMatrix = new BABYLON.Matrix();
  25647. var tempMatrix = new BABYLON.Matrix();
  25648. var matWeightIdx = 0;
  25649. var inf;
  25650. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  25651. var weight;
  25652. for (inf = 0; inf < 4; inf++) {
  25653. weight = matricesWeightsData[matWeightIdx + inf];
  25654. if (weight > 0) {
  25655. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25656. finalMatrix.addToSelf(tempMatrix);
  25657. }
  25658. else
  25659. break;
  25660. }
  25661. if (needExtras) {
  25662. for (inf = 0; inf < 4; inf++) {
  25663. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25664. if (weight > 0) {
  25665. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25666. finalMatrix.addToSelf(tempMatrix);
  25667. }
  25668. else
  25669. break;
  25670. }
  25671. }
  25672. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  25673. tempVector3.toArray(positionsData, index);
  25674. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  25675. tempVector3.toArray(normalsData, index);
  25676. finalMatrix.reset();
  25677. }
  25678. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  25679. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  25680. return this;
  25681. };
  25682. // Tools
  25683. /**
  25684. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  25685. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  25686. */
  25687. Mesh.MinMax = function (meshes) {
  25688. var minVector = null;
  25689. var maxVector = null;
  25690. meshes.forEach(function (mesh, index, array) {
  25691. var boundingInfo = mesh.getBoundingInfo();
  25692. var boundingBox = boundingInfo.boundingBox;
  25693. if (!minVector || !maxVector) {
  25694. minVector = boundingBox.minimumWorld;
  25695. maxVector = boundingBox.maximumWorld;
  25696. }
  25697. else {
  25698. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  25699. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  25700. }
  25701. });
  25702. if (!minVector || !maxVector) {
  25703. return {
  25704. min: BABYLON.Vector3.Zero(),
  25705. max: BABYLON.Vector3.Zero()
  25706. };
  25707. }
  25708. return {
  25709. min: minVector,
  25710. max: maxVector
  25711. };
  25712. };
  25713. /**
  25714. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  25715. */
  25716. Mesh.Center = function (meshesOrMinMaxVector) {
  25717. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  25718. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  25719. };
  25720. /**
  25721. * Merge the array of meshes into a single mesh for performance reasons.
  25722. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  25723. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  25724. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  25725. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  25726. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  25727. */
  25728. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  25729. if (disposeSource === void 0) { disposeSource = true; }
  25730. var index;
  25731. if (!allow32BitsIndices) {
  25732. var totalVertices = 0;
  25733. // Counting vertices
  25734. for (index = 0; index < meshes.length; index++) {
  25735. if (meshes[index]) {
  25736. totalVertices += meshes[index].getTotalVertices();
  25737. if (totalVertices > 65536) {
  25738. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  25739. return null;
  25740. }
  25741. }
  25742. }
  25743. }
  25744. // Merge
  25745. var vertexData = null;
  25746. var otherVertexData;
  25747. var indiceArray = new Array();
  25748. var source = null;
  25749. for (index = 0; index < meshes.length; index++) {
  25750. if (meshes[index]) {
  25751. meshes[index].computeWorldMatrix(true);
  25752. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  25753. otherVertexData.transform(meshes[index].getWorldMatrix());
  25754. if (vertexData) {
  25755. vertexData.merge(otherVertexData);
  25756. }
  25757. else {
  25758. vertexData = otherVertexData;
  25759. source = meshes[index];
  25760. }
  25761. if (subdivideWithSubMeshes) {
  25762. indiceArray.push(meshes[index].getTotalIndices());
  25763. }
  25764. }
  25765. }
  25766. source = source;
  25767. if (!meshSubclass) {
  25768. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  25769. }
  25770. vertexData.applyToMesh(meshSubclass);
  25771. // Setting properties
  25772. meshSubclass.material = source.material;
  25773. meshSubclass.checkCollisions = source.checkCollisions;
  25774. // Cleaning
  25775. if (disposeSource) {
  25776. for (index = 0; index < meshes.length; index++) {
  25777. if (meshes[index]) {
  25778. meshes[index].dispose();
  25779. }
  25780. }
  25781. }
  25782. // Subdivide
  25783. if (subdivideWithSubMeshes) {
  25784. //-- Suppresions du submesh global
  25785. meshSubclass.releaseSubMeshes();
  25786. index = 0;
  25787. var offset = 0;
  25788. //-- aplique la subdivision en fonction du tableau d'indices
  25789. while (index < indiceArray.length) {
  25790. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  25791. offset += indiceArray[index];
  25792. index++;
  25793. }
  25794. }
  25795. return meshSubclass;
  25796. };
  25797. // Consts
  25798. Mesh._FRONTSIDE = 0;
  25799. Mesh._BACKSIDE = 1;
  25800. Mesh._DOUBLESIDE = 2;
  25801. Mesh._DEFAULTSIDE = 0;
  25802. Mesh._NO_CAP = 0;
  25803. Mesh._CAP_START = 1;
  25804. Mesh._CAP_END = 2;
  25805. Mesh._CAP_ALL = 3;
  25806. return Mesh;
  25807. }(BABYLON.AbstractMesh));
  25808. BABYLON.Mesh = Mesh;
  25809. })(BABYLON || (BABYLON = {}));
  25810. //# sourceMappingURL=babylon.mesh.js.map
  25811. var BABYLON;
  25812. (function (BABYLON) {
  25813. var BaseSubMesh = /** @class */ (function () {
  25814. function BaseSubMesh() {
  25815. }
  25816. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  25817. get: function () {
  25818. return this._materialEffect;
  25819. },
  25820. enumerable: true,
  25821. configurable: true
  25822. });
  25823. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  25824. if (defines === void 0) { defines = null; }
  25825. if (this._materialEffect === effect) {
  25826. if (!effect) {
  25827. this._materialDefines = null;
  25828. }
  25829. return;
  25830. }
  25831. this._materialDefines = defines;
  25832. this._materialEffect = effect;
  25833. };
  25834. return BaseSubMesh;
  25835. }());
  25836. BABYLON.BaseSubMesh = BaseSubMesh;
  25837. var SubMesh = /** @class */ (function (_super) {
  25838. __extends(SubMesh, _super);
  25839. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25840. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25841. var _this = _super.call(this) || this;
  25842. _this.materialIndex = materialIndex;
  25843. _this.verticesStart = verticesStart;
  25844. _this.verticesCount = verticesCount;
  25845. _this.indexStart = indexStart;
  25846. _this.indexCount = indexCount;
  25847. _this._renderId = 0;
  25848. _this._mesh = mesh;
  25849. _this._renderingMesh = renderingMesh || mesh;
  25850. mesh.subMeshes.push(_this);
  25851. _this._trianglePlanes = [];
  25852. _this._id = mesh.subMeshes.length - 1;
  25853. if (createBoundingBox) {
  25854. _this.refreshBoundingInfo();
  25855. mesh.computeWorldMatrix(true);
  25856. }
  25857. return _this;
  25858. }
  25859. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25860. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25861. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  25862. };
  25863. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  25864. get: function () {
  25865. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  25866. },
  25867. enumerable: true,
  25868. configurable: true
  25869. });
  25870. /**
  25871. * Returns the submesh BoudingInfo object.
  25872. */
  25873. SubMesh.prototype.getBoundingInfo = function () {
  25874. if (this.IsGlobal) {
  25875. return this._mesh.getBoundingInfo();
  25876. }
  25877. return this._boundingInfo;
  25878. };
  25879. /**
  25880. * Sets the submesh BoundingInfo.
  25881. * Return the SubMesh.
  25882. */
  25883. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  25884. this._boundingInfo = boundingInfo;
  25885. return this;
  25886. };
  25887. /**
  25888. * Returns the mesh of the current submesh.
  25889. */
  25890. SubMesh.prototype.getMesh = function () {
  25891. return this._mesh;
  25892. };
  25893. /**
  25894. * Returns the rendering mesh of the submesh.
  25895. */
  25896. SubMesh.prototype.getRenderingMesh = function () {
  25897. return this._renderingMesh;
  25898. };
  25899. /**
  25900. * Returns the submesh material.
  25901. */
  25902. SubMesh.prototype.getMaterial = function () {
  25903. var rootMaterial = this._renderingMesh.material;
  25904. if (rootMaterial && rootMaterial.getSubMaterial) {
  25905. var multiMaterial = rootMaterial;
  25906. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  25907. if (this._currentMaterial !== effectiveMaterial) {
  25908. this._currentMaterial = effectiveMaterial;
  25909. this._materialDefines = null;
  25910. }
  25911. return effectiveMaterial;
  25912. }
  25913. if (!rootMaterial) {
  25914. return this._mesh.getScene().defaultMaterial;
  25915. }
  25916. return rootMaterial;
  25917. };
  25918. // Methods
  25919. /**
  25920. * Sets a new updated BoundingInfo object to the submesh.
  25921. * Returns the SubMesh.
  25922. */
  25923. SubMesh.prototype.refreshBoundingInfo = function () {
  25924. this._lastColliderWorldVertices = null;
  25925. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  25926. return this;
  25927. }
  25928. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25929. if (!data) {
  25930. this._boundingInfo = this._mesh.getBoundingInfo();
  25931. return this;
  25932. }
  25933. var indices = this._renderingMesh.getIndices();
  25934. var extend;
  25935. //is this the only submesh?
  25936. if (this.indexStart === 0 && this.indexCount === indices.length) {
  25937. var boundingInfo = this._renderingMesh.getBoundingInfo();
  25938. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  25939. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  25940. }
  25941. else {
  25942. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  25943. }
  25944. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25945. return this;
  25946. };
  25947. SubMesh.prototype._checkCollision = function (collider) {
  25948. var boundingInfo = this._renderingMesh.getBoundingInfo();
  25949. return boundingInfo._checkCollision(collider);
  25950. };
  25951. /**
  25952. * Updates the submesh BoundingInfo.
  25953. * Returns the Submesh.
  25954. */
  25955. SubMesh.prototype.updateBoundingInfo = function (world) {
  25956. var boundingInfo = this.getBoundingInfo();
  25957. if (!boundingInfo) {
  25958. this.refreshBoundingInfo();
  25959. boundingInfo = this.getBoundingInfo();
  25960. }
  25961. boundingInfo.update(world);
  25962. return this;
  25963. };
  25964. /**
  25965. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  25966. * Boolean returned.
  25967. */
  25968. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  25969. var boundingInfo = this.getBoundingInfo();
  25970. if (!boundingInfo) {
  25971. return false;
  25972. }
  25973. return boundingInfo.isInFrustum(frustumPlanes);
  25974. };
  25975. /**
  25976. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  25977. * Boolean returned.
  25978. */
  25979. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  25980. var boundingInfo = this.getBoundingInfo();
  25981. if (!boundingInfo) {
  25982. return false;
  25983. }
  25984. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  25985. };
  25986. /**
  25987. * Renders the submesh.
  25988. * Returns it.
  25989. */
  25990. SubMesh.prototype.render = function (enableAlphaMode) {
  25991. this._renderingMesh.render(this, enableAlphaMode);
  25992. return this;
  25993. };
  25994. /**
  25995. * Returns a new Index Buffer.
  25996. * Type returned : WebGLBuffer.
  25997. */
  25998. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  25999. if (!this._linesIndexBuffer) {
  26000. var linesIndices = [];
  26001. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  26002. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  26003. }
  26004. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  26005. this.linesIndexCount = linesIndices.length;
  26006. }
  26007. return this._linesIndexBuffer;
  26008. };
  26009. /**
  26010. * True is the passed Ray intersects the submesh bounding box.
  26011. * Boolean returned.
  26012. */
  26013. SubMesh.prototype.canIntersects = function (ray) {
  26014. var boundingInfo = this.getBoundingInfo();
  26015. if (!boundingInfo) {
  26016. return false;
  26017. }
  26018. return ray.intersectsBox(boundingInfo.boundingBox);
  26019. };
  26020. /**
  26021. * Returns an object IntersectionInfo.
  26022. */
  26023. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  26024. var intersectInfo = null;
  26025. // LineMesh first as it's also a Mesh...
  26026. if (this._mesh instanceof BABYLON.LinesMesh) {
  26027. var lineMesh = this._mesh;
  26028. // Line test
  26029. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  26030. var p0 = positions[indices[index]];
  26031. var p1 = positions[indices[index + 1]];
  26032. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  26033. if (length < 0) {
  26034. continue;
  26035. }
  26036. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  26037. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  26038. if (fastCheck) {
  26039. break;
  26040. }
  26041. }
  26042. }
  26043. }
  26044. else {
  26045. // Triangles test
  26046. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  26047. var p0 = positions[indices[index]];
  26048. var p1 = positions[indices[index + 1]];
  26049. var p2 = positions[indices[index + 2]];
  26050. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  26051. if (currentIntersectInfo) {
  26052. if (currentIntersectInfo.distance < 0) {
  26053. continue;
  26054. }
  26055. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  26056. intersectInfo = currentIntersectInfo;
  26057. intersectInfo.faceId = index / 3;
  26058. if (fastCheck) {
  26059. break;
  26060. }
  26061. }
  26062. }
  26063. }
  26064. }
  26065. return intersectInfo;
  26066. };
  26067. SubMesh.prototype._rebuild = function () {
  26068. if (this._linesIndexBuffer) {
  26069. this._linesIndexBuffer = null;
  26070. }
  26071. };
  26072. // Clone
  26073. /**
  26074. * Creates a new Submesh from the passed Mesh.
  26075. */
  26076. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  26077. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  26078. if (!this.IsGlobal) {
  26079. var boundingInfo = this.getBoundingInfo();
  26080. if (!boundingInfo) {
  26081. return result;
  26082. }
  26083. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  26084. }
  26085. return result;
  26086. };
  26087. // Dispose
  26088. /**
  26089. * Disposes the Submesh.
  26090. * Returns nothing.
  26091. */
  26092. SubMesh.prototype.dispose = function () {
  26093. if (this._linesIndexBuffer) {
  26094. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  26095. this._linesIndexBuffer = null;
  26096. }
  26097. // Remove from mesh
  26098. var index = this._mesh.subMeshes.indexOf(this);
  26099. this._mesh.subMeshes.splice(index, 1);
  26100. };
  26101. // Statics
  26102. /**
  26103. * Creates a new Submesh from the passed parameters :
  26104. * - materialIndex (integer) : the index of the main mesh material.
  26105. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  26106. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  26107. * - mesh (Mesh) : the main mesh to create the submesh from.
  26108. * - renderingMesh (optional Mesh) : rendering mesh.
  26109. */
  26110. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  26111. var minVertexIndex = Number.MAX_VALUE;
  26112. var maxVertexIndex = -Number.MAX_VALUE;
  26113. renderingMesh = (renderingMesh || mesh);
  26114. var indices = renderingMesh.getIndices();
  26115. for (var index = startIndex; index < startIndex + indexCount; index++) {
  26116. var vertexIndex = indices[index];
  26117. if (vertexIndex < minVertexIndex)
  26118. minVertexIndex = vertexIndex;
  26119. if (vertexIndex > maxVertexIndex)
  26120. maxVertexIndex = vertexIndex;
  26121. }
  26122. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  26123. };
  26124. return SubMesh;
  26125. }(BaseSubMesh));
  26126. BABYLON.SubMesh = SubMesh;
  26127. })(BABYLON || (BABYLON = {}));
  26128. //# sourceMappingURL=babylon.subMesh.js.map
  26129. var BABYLON;
  26130. (function (BABYLON) {
  26131. var EffectFallbacks = /** @class */ (function () {
  26132. function EffectFallbacks() {
  26133. this._defines = {};
  26134. this._currentRank = 32;
  26135. this._maxRank = -1;
  26136. }
  26137. EffectFallbacks.prototype.unBindMesh = function () {
  26138. this._mesh = null;
  26139. };
  26140. EffectFallbacks.prototype.addFallback = function (rank, define) {
  26141. if (!this._defines[rank]) {
  26142. if (rank < this._currentRank) {
  26143. this._currentRank = rank;
  26144. }
  26145. if (rank > this._maxRank) {
  26146. this._maxRank = rank;
  26147. }
  26148. this._defines[rank] = new Array();
  26149. }
  26150. this._defines[rank].push(define);
  26151. };
  26152. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  26153. this._mesh = mesh;
  26154. if (rank < this._currentRank) {
  26155. this._currentRank = rank;
  26156. }
  26157. if (rank > this._maxRank) {
  26158. this._maxRank = rank;
  26159. }
  26160. };
  26161. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  26162. get: function () {
  26163. return this._currentRank <= this._maxRank;
  26164. },
  26165. enumerable: true,
  26166. configurable: true
  26167. });
  26168. EffectFallbacks.prototype.reduce = function (currentDefines) {
  26169. // First we try to switch to CPU skinning
  26170. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  26171. this._mesh.computeBonesUsingShaders = false;
  26172. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  26173. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  26174. var scene = this._mesh.getScene();
  26175. for (var index = 0; index < scene.meshes.length; index++) {
  26176. var otherMesh = scene.meshes[index];
  26177. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  26178. otherMesh.computeBonesUsingShaders = false;
  26179. }
  26180. }
  26181. }
  26182. else {
  26183. var currentFallbacks = this._defines[this._currentRank];
  26184. if (currentFallbacks) {
  26185. for (var index = 0; index < currentFallbacks.length; index++) {
  26186. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  26187. }
  26188. }
  26189. this._currentRank++;
  26190. }
  26191. return currentDefines;
  26192. };
  26193. return EffectFallbacks;
  26194. }());
  26195. BABYLON.EffectFallbacks = EffectFallbacks;
  26196. var EffectCreationOptions = /** @class */ (function () {
  26197. function EffectCreationOptions() {
  26198. }
  26199. return EffectCreationOptions;
  26200. }());
  26201. BABYLON.EffectCreationOptions = EffectCreationOptions;
  26202. var Effect = /** @class */ (function () {
  26203. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  26204. if (samplers === void 0) { samplers = null; }
  26205. if (defines === void 0) { defines = null; }
  26206. if (fallbacks === void 0) { fallbacks = null; }
  26207. if (onCompiled === void 0) { onCompiled = null; }
  26208. if (onError === void 0) { onError = null; }
  26209. var _this = this;
  26210. this.uniqueId = 0;
  26211. this.onCompileObservable = new BABYLON.Observable();
  26212. this.onErrorObservable = new BABYLON.Observable();
  26213. this.onBindObservable = new BABYLON.Observable();
  26214. this._uniformBuffersNames = {};
  26215. this._isReady = false;
  26216. this._compilationError = "";
  26217. this.name = baseName;
  26218. if (attributesNamesOrOptions.attributes) {
  26219. var options = attributesNamesOrOptions;
  26220. this._engine = uniformsNamesOrEngine;
  26221. this._attributesNames = options.attributes;
  26222. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  26223. this._samplers = options.samplers;
  26224. this.defines = options.defines;
  26225. this.onError = options.onError;
  26226. this.onCompiled = options.onCompiled;
  26227. this._fallbacks = options.fallbacks;
  26228. this._indexParameters = options.indexParameters;
  26229. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  26230. if (options.uniformBuffersNames) {
  26231. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  26232. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  26233. }
  26234. }
  26235. }
  26236. else {
  26237. this._engine = engine;
  26238. this.defines = defines;
  26239. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  26240. this._samplers = samplers;
  26241. this._attributesNames = attributesNamesOrOptions;
  26242. this.onError = onError;
  26243. this.onCompiled = onCompiled;
  26244. this._indexParameters = indexParameters;
  26245. this._fallbacks = fallbacks;
  26246. }
  26247. this.uniqueId = Effect._uniqueIdSeed++;
  26248. var vertexSource;
  26249. var fragmentSource;
  26250. if (baseName.vertexElement) {
  26251. vertexSource = document.getElementById(baseName.vertexElement);
  26252. if (!vertexSource) {
  26253. vertexSource = baseName.vertexElement;
  26254. }
  26255. }
  26256. else {
  26257. vertexSource = baseName.vertex || baseName;
  26258. }
  26259. if (baseName.fragmentElement) {
  26260. fragmentSource = document.getElementById(baseName.fragmentElement);
  26261. if (!fragmentSource) {
  26262. fragmentSource = baseName.fragmentElement;
  26263. }
  26264. }
  26265. else {
  26266. fragmentSource = baseName.fragment || baseName;
  26267. }
  26268. this._loadVertexShader(vertexSource, function (vertexCode) {
  26269. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  26270. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  26271. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  26272. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  26273. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  26274. if (baseName) {
  26275. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  26276. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  26277. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  26278. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  26279. }
  26280. else {
  26281. _this._vertexSourceCode = migratedVertexCode;
  26282. _this._fragmentSourceCode = migratedFragmentCode;
  26283. }
  26284. _this._prepareEffect();
  26285. });
  26286. });
  26287. });
  26288. });
  26289. });
  26290. });
  26291. }
  26292. Object.defineProperty(Effect.prototype, "key", {
  26293. get: function () {
  26294. return this._key;
  26295. },
  26296. enumerable: true,
  26297. configurable: true
  26298. });
  26299. // Properties
  26300. Effect.prototype.isReady = function () {
  26301. return this._isReady;
  26302. };
  26303. Effect.prototype.getEngine = function () {
  26304. return this._engine;
  26305. };
  26306. Effect.prototype.getProgram = function () {
  26307. return this._program;
  26308. };
  26309. Effect.prototype.getAttributesNames = function () {
  26310. return this._attributesNames;
  26311. };
  26312. Effect.prototype.getAttributeLocation = function (index) {
  26313. return this._attributes[index];
  26314. };
  26315. Effect.prototype.getAttributeLocationByName = function (name) {
  26316. var index = this._attributesNames.indexOf(name);
  26317. return this._attributes[index];
  26318. };
  26319. Effect.prototype.getAttributesCount = function () {
  26320. return this._attributes.length;
  26321. };
  26322. Effect.prototype.getUniformIndex = function (uniformName) {
  26323. return this._uniformsNames.indexOf(uniformName);
  26324. };
  26325. Effect.prototype.getUniform = function (uniformName) {
  26326. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  26327. };
  26328. Effect.prototype.getSamplers = function () {
  26329. return this._samplers;
  26330. };
  26331. Effect.prototype.getCompilationError = function () {
  26332. return this._compilationError;
  26333. };
  26334. // Methods
  26335. Effect.prototype.executeWhenCompiled = function (func) {
  26336. if (this.isReady()) {
  26337. func(this);
  26338. return;
  26339. }
  26340. this.onCompileObservable.add(function (effect) {
  26341. func(effect);
  26342. });
  26343. };
  26344. Effect.prototype._loadVertexShader = function (vertex, callback) {
  26345. if (BABYLON.Tools.IsWindowObjectExist()) {
  26346. // DOM element ?
  26347. if (vertex instanceof HTMLElement) {
  26348. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  26349. callback(vertexCode);
  26350. return;
  26351. }
  26352. }
  26353. // Base64 encoded ?
  26354. if (vertex.substr(0, 7) === "base64:") {
  26355. var vertexBinary = window.atob(vertex.substr(7));
  26356. callback(vertexBinary);
  26357. return;
  26358. }
  26359. // Is in local store ?
  26360. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  26361. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  26362. return;
  26363. }
  26364. var vertexShaderUrl;
  26365. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  26366. vertexShaderUrl = vertex;
  26367. }
  26368. else {
  26369. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  26370. }
  26371. // Vertex shader
  26372. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  26373. };
  26374. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  26375. if (BABYLON.Tools.IsWindowObjectExist()) {
  26376. // DOM element ?
  26377. if (fragment instanceof HTMLElement) {
  26378. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  26379. callback(fragmentCode);
  26380. return;
  26381. }
  26382. }
  26383. // Base64 encoded ?
  26384. if (fragment.substr(0, 7) === "base64:") {
  26385. var fragmentBinary = window.atob(fragment.substr(7));
  26386. callback(fragmentBinary);
  26387. return;
  26388. }
  26389. // Is in local store ?
  26390. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  26391. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  26392. return;
  26393. }
  26394. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  26395. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  26396. return;
  26397. }
  26398. var fragmentShaderUrl;
  26399. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  26400. fragmentShaderUrl = fragment;
  26401. }
  26402. else {
  26403. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  26404. }
  26405. // Fragment shader
  26406. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  26407. };
  26408. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  26409. // Rebuild shaders source code
  26410. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  26411. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  26412. vertexCode = prefix + vertexCode;
  26413. fragmentCode = prefix + fragmentCode;
  26414. // Number lines of shaders source code
  26415. var i = 2;
  26416. var regex = /\n/gm;
  26417. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  26418. i = 2;
  26419. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  26420. // Dump shaders name and formatted source code
  26421. if (this.name.vertexElement) {
  26422. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  26423. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  26424. }
  26425. else if (this.name.vertex) {
  26426. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  26427. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  26428. }
  26429. else {
  26430. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  26431. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  26432. }
  26433. };
  26434. ;
  26435. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  26436. var preparedSourceCode = this._processPrecision(sourceCode);
  26437. if (this._engine.webGLVersion == 1) {
  26438. callback(preparedSourceCode);
  26439. return;
  26440. }
  26441. // Already converted
  26442. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  26443. callback(preparedSourceCode.replace("#version 300 es", ""));
  26444. return;
  26445. }
  26446. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  26447. // Remove extensions
  26448. // #extension GL_OES_standard_derivatives : enable
  26449. // #extension GL_EXT_shader_texture_lod : enable
  26450. // #extension GL_EXT_frag_depth : enable
  26451. // #extension GL_EXT_draw_buffers : require
  26452. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  26453. var result = preparedSourceCode.replace(regex, "");
  26454. // Migrate to GLSL v300
  26455. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  26456. result = result.replace(/attribute[ \t]/g, "in ");
  26457. result = result.replace(/[ \t]attribute/g, " in");
  26458. if (isFragment) {
  26459. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  26460. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  26461. result = result.replace(/texture2D\s*\(/g, "texture(");
  26462. result = result.replace(/textureCube\s*\(/g, "texture(");
  26463. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  26464. result = result.replace(/gl_FragColor/g, "glFragColor");
  26465. result = result.replace(/gl_FragData/g, "glFragData");
  26466. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  26467. }
  26468. callback(result);
  26469. };
  26470. Effect.prototype._processIncludes = function (sourceCode, callback) {
  26471. var _this = this;
  26472. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  26473. var match = regex.exec(sourceCode);
  26474. var returnValue = new String(sourceCode);
  26475. while (match != null) {
  26476. var includeFile = match[1];
  26477. // Uniform declaration
  26478. if (includeFile.indexOf("__decl__") !== -1) {
  26479. includeFile = includeFile.replace(/__decl__/, "");
  26480. if (this._engine.supportsUniformBuffers) {
  26481. includeFile = includeFile.replace(/Vertex/, "Ubo");
  26482. includeFile = includeFile.replace(/Fragment/, "Ubo");
  26483. }
  26484. includeFile = includeFile + "Declaration";
  26485. }
  26486. if (Effect.IncludesShadersStore[includeFile]) {
  26487. // Substitution
  26488. var includeContent = Effect.IncludesShadersStore[includeFile];
  26489. if (match[2]) {
  26490. var splits = match[3].split(",");
  26491. for (var index = 0; index < splits.length; index += 2) {
  26492. var source = new RegExp(splits[index], "g");
  26493. var dest = splits[index + 1];
  26494. includeContent = includeContent.replace(source, dest);
  26495. }
  26496. }
  26497. if (match[4]) {
  26498. var indexString = match[5];
  26499. if (indexString.indexOf("..") !== -1) {
  26500. var indexSplits = indexString.split("..");
  26501. var minIndex = parseInt(indexSplits[0]);
  26502. var maxIndex = parseInt(indexSplits[1]);
  26503. var sourceIncludeContent = includeContent.slice(0);
  26504. includeContent = "";
  26505. if (isNaN(maxIndex)) {
  26506. maxIndex = this._indexParameters[indexSplits[1]];
  26507. }
  26508. for (var i = minIndex; i < maxIndex; i++) {
  26509. if (!this._engine.supportsUniformBuffers) {
  26510. // Ubo replacement
  26511. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  26512. return p1 + "{X}";
  26513. });
  26514. }
  26515. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  26516. }
  26517. }
  26518. else {
  26519. if (!this._engine.supportsUniformBuffers) {
  26520. // Ubo replacement
  26521. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  26522. return p1 + "{X}";
  26523. });
  26524. }
  26525. includeContent = includeContent.replace(/\{X\}/g, indexString);
  26526. }
  26527. }
  26528. // Replace
  26529. returnValue = returnValue.replace(match[0], includeContent);
  26530. }
  26531. else {
  26532. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  26533. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  26534. Effect.IncludesShadersStore[includeFile] = fileContent;
  26535. _this._processIncludes(returnValue, callback);
  26536. });
  26537. return;
  26538. }
  26539. match = regex.exec(sourceCode);
  26540. }
  26541. callback(returnValue);
  26542. };
  26543. Effect.prototype._processPrecision = function (source) {
  26544. if (source.indexOf("precision highp float") === -1) {
  26545. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26546. source = "precision mediump float;\n" + source;
  26547. }
  26548. else {
  26549. source = "precision highp float;\n" + source;
  26550. }
  26551. }
  26552. else {
  26553. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26554. source = source.replace("precision highp float", "precision mediump float");
  26555. }
  26556. }
  26557. return source;
  26558. };
  26559. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  26560. var _this = this;
  26561. this._isReady = false;
  26562. this._vertexSourceCodeOverride = vertexSourceCode;
  26563. this._fragmentSourceCodeOverride = fragmentSourceCode;
  26564. this.onError = function (effect, error) {
  26565. if (onError) {
  26566. onError(error);
  26567. }
  26568. };
  26569. this.onCompiled = function () {
  26570. var scenes = _this.getEngine().scenes;
  26571. for (var i = 0; i < scenes.length; i++) {
  26572. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26573. }
  26574. if (onCompiled) {
  26575. onCompiled(_this._program);
  26576. }
  26577. };
  26578. this._fallbacks = null;
  26579. this._prepareEffect();
  26580. };
  26581. Effect.prototype._prepareEffect = function () {
  26582. var attributesNames = this._attributesNames;
  26583. var defines = this.defines;
  26584. var fallbacks = this._fallbacks;
  26585. this._valueCache = {};
  26586. var previousProgram = this._program;
  26587. try {
  26588. var engine = this._engine;
  26589. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  26590. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  26591. }
  26592. else {
  26593. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  26594. }
  26595. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  26596. if (engine.webGLVersion > 1) {
  26597. for (var name in this._uniformBuffersNames) {
  26598. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  26599. }
  26600. }
  26601. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  26602. this._attributes = engine.getAttributes(this._program, attributesNames);
  26603. var index;
  26604. for (index = 0; index < this._samplers.length; index++) {
  26605. var sampler = this.getUniform(this._samplers[index]);
  26606. if (sampler == null) {
  26607. this._samplers.splice(index, 1);
  26608. index--;
  26609. }
  26610. }
  26611. engine.bindSamplers(this);
  26612. this._compilationError = "";
  26613. this._isReady = true;
  26614. if (this.onCompiled) {
  26615. this.onCompiled(this);
  26616. }
  26617. this.onCompileObservable.notifyObservers(this);
  26618. this.onCompileObservable.clear();
  26619. // Unbind mesh reference in fallbacks
  26620. if (this._fallbacks) {
  26621. this._fallbacks.unBindMesh();
  26622. }
  26623. if (previousProgram) {
  26624. this.getEngine()._deleteProgram(previousProgram);
  26625. }
  26626. }
  26627. catch (e) {
  26628. this._compilationError = e.message;
  26629. // Let's go through fallbacks then
  26630. BABYLON.Tools.Error("Unable to compile effect:");
  26631. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  26632. return " " + uniform;
  26633. }));
  26634. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  26635. return " " + attribute;
  26636. }));
  26637. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  26638. BABYLON.Tools.Error("Error: " + this._compilationError);
  26639. if (previousProgram) {
  26640. this._program = previousProgram;
  26641. this._isReady = true;
  26642. if (this.onError) {
  26643. this.onError(this, this._compilationError);
  26644. }
  26645. this.onErrorObservable.notifyObservers(this);
  26646. }
  26647. if (fallbacks && fallbacks.isMoreFallbacks) {
  26648. BABYLON.Tools.Error("Trying next fallback.");
  26649. this.defines = fallbacks.reduce(this.defines);
  26650. this._prepareEffect();
  26651. }
  26652. else {
  26653. if (this.onError) {
  26654. this.onError(this, this._compilationError);
  26655. }
  26656. this.onErrorObservable.notifyObservers(this);
  26657. this.onErrorObservable.clear();
  26658. // Unbind mesh reference in fallbacks
  26659. if (this._fallbacks) {
  26660. this._fallbacks.unBindMesh();
  26661. }
  26662. }
  26663. }
  26664. };
  26665. Object.defineProperty(Effect.prototype, "isSupported", {
  26666. get: function () {
  26667. return this._compilationError === "";
  26668. },
  26669. enumerable: true,
  26670. configurable: true
  26671. });
  26672. Effect.prototype._bindTexture = function (channel, texture) {
  26673. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  26674. };
  26675. Effect.prototype.setTexture = function (channel, texture) {
  26676. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  26677. };
  26678. Effect.prototype.setTextureArray = function (channel, textures) {
  26679. if (this._samplers.indexOf(channel + "Ex") === -1) {
  26680. var initialPos = this._samplers.indexOf(channel);
  26681. for (var index = 1; index < textures.length; index++) {
  26682. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  26683. }
  26684. }
  26685. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  26686. };
  26687. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  26688. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  26689. };
  26690. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  26691. var cache = this._valueCache[uniformName];
  26692. var flag = matrix.updateFlag;
  26693. if (cache !== undefined && cache === flag) {
  26694. return false;
  26695. }
  26696. this._valueCache[uniformName] = flag;
  26697. return true;
  26698. };
  26699. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  26700. var cache = this._valueCache[uniformName];
  26701. if (!cache) {
  26702. cache = [x, y];
  26703. this._valueCache[uniformName] = cache;
  26704. return true;
  26705. }
  26706. var changed = false;
  26707. if (cache[0] !== x) {
  26708. cache[0] = x;
  26709. changed = true;
  26710. }
  26711. if (cache[1] !== y) {
  26712. cache[1] = y;
  26713. changed = true;
  26714. }
  26715. return changed;
  26716. };
  26717. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  26718. var cache = this._valueCache[uniformName];
  26719. if (!cache) {
  26720. cache = [x, y, z];
  26721. this._valueCache[uniformName] = cache;
  26722. return true;
  26723. }
  26724. var changed = false;
  26725. if (cache[0] !== x) {
  26726. cache[0] = x;
  26727. changed = true;
  26728. }
  26729. if (cache[1] !== y) {
  26730. cache[1] = y;
  26731. changed = true;
  26732. }
  26733. if (cache[2] !== z) {
  26734. cache[2] = z;
  26735. changed = true;
  26736. }
  26737. return changed;
  26738. };
  26739. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  26740. var cache = this._valueCache[uniformName];
  26741. if (!cache) {
  26742. cache = [x, y, z, w];
  26743. this._valueCache[uniformName] = cache;
  26744. return true;
  26745. }
  26746. var changed = false;
  26747. if (cache[0] !== x) {
  26748. cache[0] = x;
  26749. changed = true;
  26750. }
  26751. if (cache[1] !== y) {
  26752. cache[1] = y;
  26753. changed = true;
  26754. }
  26755. if (cache[2] !== z) {
  26756. cache[2] = z;
  26757. changed = true;
  26758. }
  26759. if (cache[3] !== w) {
  26760. cache[3] = w;
  26761. changed = true;
  26762. }
  26763. return changed;
  26764. };
  26765. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  26766. var bufferName = this._uniformBuffersNames[name];
  26767. if (Effect._baseCache[bufferName] === buffer) {
  26768. return;
  26769. }
  26770. Effect._baseCache[bufferName] = buffer;
  26771. this._engine.bindUniformBufferBase(buffer, bufferName);
  26772. };
  26773. Effect.prototype.bindUniformBlock = function (blockName, index) {
  26774. this._engine.bindUniformBlock(this._program, blockName, index);
  26775. };
  26776. Effect.prototype.setIntArray = function (uniformName, array) {
  26777. this._valueCache[uniformName] = null;
  26778. this._engine.setIntArray(this.getUniform(uniformName), array);
  26779. return this;
  26780. };
  26781. Effect.prototype.setIntArray2 = function (uniformName, array) {
  26782. this._valueCache[uniformName] = null;
  26783. this._engine.setIntArray2(this.getUniform(uniformName), array);
  26784. return this;
  26785. };
  26786. Effect.prototype.setIntArray3 = function (uniformName, array) {
  26787. this._valueCache[uniformName] = null;
  26788. this._engine.setIntArray3(this.getUniform(uniformName), array);
  26789. return this;
  26790. };
  26791. Effect.prototype.setIntArray4 = function (uniformName, array) {
  26792. this._valueCache[uniformName] = null;
  26793. this._engine.setIntArray4(this.getUniform(uniformName), array);
  26794. return this;
  26795. };
  26796. Effect.prototype.setFloatArray = function (uniformName, array) {
  26797. this._valueCache[uniformName] = null;
  26798. this._engine.setFloatArray(this.getUniform(uniformName), array);
  26799. return this;
  26800. };
  26801. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  26802. this._valueCache[uniformName] = null;
  26803. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  26804. return this;
  26805. };
  26806. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  26807. this._valueCache[uniformName] = null;
  26808. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  26809. return this;
  26810. };
  26811. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  26812. this._valueCache[uniformName] = null;
  26813. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  26814. return this;
  26815. };
  26816. Effect.prototype.setArray = function (uniformName, array) {
  26817. this._valueCache[uniformName] = null;
  26818. this._engine.setArray(this.getUniform(uniformName), array);
  26819. return this;
  26820. };
  26821. Effect.prototype.setArray2 = function (uniformName, array) {
  26822. this._valueCache[uniformName] = null;
  26823. this._engine.setArray2(this.getUniform(uniformName), array);
  26824. return this;
  26825. };
  26826. Effect.prototype.setArray3 = function (uniformName, array) {
  26827. this._valueCache[uniformName] = null;
  26828. this._engine.setArray3(this.getUniform(uniformName), array);
  26829. return this;
  26830. };
  26831. Effect.prototype.setArray4 = function (uniformName, array) {
  26832. this._valueCache[uniformName] = null;
  26833. this._engine.setArray4(this.getUniform(uniformName), array);
  26834. return this;
  26835. };
  26836. Effect.prototype.setMatrices = function (uniformName, matrices) {
  26837. if (!matrices) {
  26838. return this;
  26839. }
  26840. this._valueCache[uniformName] = null;
  26841. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  26842. return this;
  26843. };
  26844. Effect.prototype.setMatrix = function (uniformName, matrix) {
  26845. if (this._cacheMatrix(uniformName, matrix)) {
  26846. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  26847. }
  26848. return this;
  26849. };
  26850. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  26851. this._valueCache[uniformName] = null;
  26852. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  26853. return this;
  26854. };
  26855. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  26856. this._valueCache[uniformName] = null;
  26857. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  26858. return this;
  26859. };
  26860. Effect.prototype.setFloat = function (uniformName, value) {
  26861. var cache = this._valueCache[uniformName];
  26862. if (cache !== undefined && cache === value)
  26863. return this;
  26864. this._valueCache[uniformName] = value;
  26865. this._engine.setFloat(this.getUniform(uniformName), value);
  26866. return this;
  26867. };
  26868. Effect.prototype.setBool = function (uniformName, bool) {
  26869. var cache = this._valueCache[uniformName];
  26870. if (cache !== undefined && cache === bool)
  26871. return this;
  26872. this._valueCache[uniformName] = bool;
  26873. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  26874. return this;
  26875. };
  26876. Effect.prototype.setVector2 = function (uniformName, vector2) {
  26877. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  26878. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  26879. }
  26880. return this;
  26881. };
  26882. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  26883. if (this._cacheFloat2(uniformName, x, y)) {
  26884. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  26885. }
  26886. return this;
  26887. };
  26888. Effect.prototype.setVector3 = function (uniformName, vector3) {
  26889. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  26890. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  26891. }
  26892. return this;
  26893. };
  26894. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  26895. if (this._cacheFloat3(uniformName, x, y, z)) {
  26896. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  26897. }
  26898. return this;
  26899. };
  26900. Effect.prototype.setVector4 = function (uniformName, vector4) {
  26901. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  26902. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  26903. }
  26904. return this;
  26905. };
  26906. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  26907. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  26908. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  26909. }
  26910. return this;
  26911. };
  26912. Effect.prototype.setColor3 = function (uniformName, color3) {
  26913. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  26914. this._engine.setColor3(this.getUniform(uniformName), color3);
  26915. }
  26916. return this;
  26917. };
  26918. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  26919. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  26920. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  26921. }
  26922. return this;
  26923. };
  26924. Effect.ResetCache = function () {
  26925. Effect._baseCache = {};
  26926. };
  26927. Effect._uniqueIdSeed = 0;
  26928. Effect._baseCache = {};
  26929. // Statics
  26930. Effect.ShadersStore = {};
  26931. Effect.IncludesShadersStore = {};
  26932. return Effect;
  26933. }());
  26934. BABYLON.Effect = Effect;
  26935. })(BABYLON || (BABYLON = {}));
  26936. //# sourceMappingURL=babylon.effect.js.map
  26937. var BABYLON;
  26938. (function (BABYLON) {
  26939. var MaterialHelper = /** @class */ (function () {
  26940. function MaterialHelper() {
  26941. }
  26942. MaterialHelper.BindEyePosition = function (effect, scene) {
  26943. if (scene._forcedViewPosition) {
  26944. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  26945. return;
  26946. }
  26947. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  26948. };
  26949. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  26950. defines._needUVs = true;
  26951. defines[key] = true;
  26952. if (texture.getTextureMatrix().isIdentity(true)) {
  26953. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  26954. if (texture.coordinatesIndex === 0) {
  26955. defines["MAINUV1"] = true;
  26956. }
  26957. else {
  26958. defines["MAINUV2"] = true;
  26959. }
  26960. }
  26961. else {
  26962. defines[key + "DIRECTUV"] = 0;
  26963. }
  26964. };
  26965. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  26966. var matrix = texture.getTextureMatrix();
  26967. if (!matrix.isIdentity(true)) {
  26968. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  26969. }
  26970. };
  26971. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  26972. if (defines._areMiscDirty) {
  26973. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  26974. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  26975. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  26976. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  26977. }
  26978. };
  26979. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  26980. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  26981. var changed = false;
  26982. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  26983. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  26984. changed = true;
  26985. }
  26986. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  26987. defines["ALPHATEST"] = !defines["ALPHATEST"];
  26988. changed = true;
  26989. }
  26990. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  26991. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  26992. changed = true;
  26993. }
  26994. if (defines["INSTANCES"] !== useInstances) {
  26995. defines["INSTANCES"] = useInstances;
  26996. changed = true;
  26997. }
  26998. if (changed) {
  26999. defines.markAsUnprocessed();
  27000. }
  27001. };
  27002. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  27003. if (useMorphTargets === void 0) { useMorphTargets = false; }
  27004. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  27005. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  27006. return false;
  27007. }
  27008. defines._normals = defines._needNormals;
  27009. defines._uvs = defines._needUVs;
  27010. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  27011. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  27012. defines["TANGENT"] = true;
  27013. }
  27014. if (defines._needUVs) {
  27015. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  27016. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  27017. }
  27018. else {
  27019. defines["UV1"] = false;
  27020. defines["UV2"] = false;
  27021. }
  27022. if (useVertexColor) {
  27023. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  27024. defines["VERTEXCOLOR"] = hasVertexColors;
  27025. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  27026. }
  27027. if (useBones) {
  27028. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  27029. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  27030. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  27031. }
  27032. else {
  27033. defines["NUM_BONE_INFLUENCERS"] = 0;
  27034. defines["BonesPerMesh"] = 0;
  27035. }
  27036. }
  27037. if (useMorphTargets) {
  27038. var manager = mesh.morphTargetManager;
  27039. if (manager) {
  27040. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  27041. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  27042. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  27043. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  27044. }
  27045. else {
  27046. defines["MORPHTARGETS_TANGENT"] = false;
  27047. defines["MORPHTARGETS_NORMAL"] = false;
  27048. defines["MORPHTARGETS"] = false;
  27049. defines["NUM_MORPH_INFLUENCERS"] = 0;
  27050. }
  27051. }
  27052. return true;
  27053. };
  27054. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  27055. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  27056. if (disableLighting === void 0) { disableLighting = false; }
  27057. if (!defines._areLightsDirty) {
  27058. return defines._needNormals;
  27059. }
  27060. var lightIndex = 0;
  27061. var needNormals = false;
  27062. var needRebuild = false;
  27063. var lightmapMode = false;
  27064. var shadowEnabled = false;
  27065. var specularEnabled = false;
  27066. if (scene.lightsEnabled && !disableLighting) {
  27067. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  27068. var light = _a[_i];
  27069. needNormals = true;
  27070. if (defines["LIGHT" + lightIndex] === undefined) {
  27071. needRebuild = true;
  27072. }
  27073. defines["LIGHT" + lightIndex] = true;
  27074. defines["SPOTLIGHT" + lightIndex] = false;
  27075. defines["HEMILIGHT" + lightIndex] = false;
  27076. defines["POINTLIGHT" + lightIndex] = false;
  27077. defines["DIRLIGHT" + lightIndex] = false;
  27078. var type;
  27079. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  27080. type = "SPOTLIGHT" + lightIndex;
  27081. }
  27082. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  27083. type = "HEMILIGHT" + lightIndex;
  27084. }
  27085. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  27086. type = "POINTLIGHT" + lightIndex;
  27087. }
  27088. else {
  27089. type = "DIRLIGHT" + lightIndex;
  27090. }
  27091. defines[type] = true;
  27092. // Specular
  27093. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  27094. specularEnabled = true;
  27095. }
  27096. // Shadows
  27097. defines["SHADOW" + lightIndex] = false;
  27098. defines["SHADOWPCF" + lightIndex] = false;
  27099. defines["SHADOWESM" + lightIndex] = false;
  27100. defines["SHADOWCUBE" + lightIndex] = false;
  27101. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  27102. var shadowGenerator = light.getShadowGenerator();
  27103. if (shadowGenerator) {
  27104. shadowEnabled = true;
  27105. shadowGenerator.prepareDefines(defines, lightIndex);
  27106. }
  27107. }
  27108. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  27109. lightmapMode = true;
  27110. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  27111. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  27112. }
  27113. else {
  27114. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  27115. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  27116. }
  27117. lightIndex++;
  27118. if (lightIndex === maxSimultaneousLights)
  27119. break;
  27120. }
  27121. }
  27122. defines["SPECULARTERM"] = specularEnabled;
  27123. defines["SHADOWS"] = shadowEnabled;
  27124. // Resetting all other lights if any
  27125. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  27126. if (defines["LIGHT" + index] !== undefined) {
  27127. defines["LIGHT" + index] = false;
  27128. defines["HEMILIGHT" + lightIndex] = false;
  27129. defines["POINTLIGHT" + lightIndex] = false;
  27130. defines["DIRLIGHT" + lightIndex] = false;
  27131. defines["SPOTLIGHT" + lightIndex] = false;
  27132. defines["SHADOW" + lightIndex] = false;
  27133. }
  27134. }
  27135. var caps = scene.getEngine().getCaps();
  27136. if (defines["SHADOWFLOAT"] === undefined) {
  27137. needRebuild = true;
  27138. }
  27139. defines["SHADOWFLOAT"] = shadowEnabled &&
  27140. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  27141. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  27142. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  27143. if (needRebuild) {
  27144. defines.rebuild();
  27145. }
  27146. return needNormals;
  27147. };
  27148. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  27149. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  27150. var uniformsList;
  27151. var uniformBuffersList = null;
  27152. if (uniformsListOrOptions.uniformsNames) {
  27153. var options = uniformsListOrOptions;
  27154. uniformsList = options.uniformsNames;
  27155. uniformBuffersList = options.uniformBuffersNames;
  27156. samplersList = options.samplers;
  27157. defines = options.defines;
  27158. maxSimultaneousLights = options.maxSimultaneousLights;
  27159. }
  27160. else {
  27161. uniformsList = uniformsListOrOptions;
  27162. if (!samplersList) {
  27163. samplersList = [];
  27164. }
  27165. }
  27166. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  27167. if (!defines["LIGHT" + lightIndex]) {
  27168. break;
  27169. }
  27170. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  27171. if (uniformBuffersList) {
  27172. uniformBuffersList.push("Light" + lightIndex);
  27173. }
  27174. samplersList.push("shadowSampler" + lightIndex);
  27175. }
  27176. if (defines["NUM_MORPH_INFLUENCERS"]) {
  27177. uniformsList.push("morphTargetInfluences");
  27178. }
  27179. };
  27180. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  27181. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  27182. if (rank === void 0) { rank = 0; }
  27183. var lightFallbackRank = 0;
  27184. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  27185. if (!defines["LIGHT" + lightIndex]) {
  27186. break;
  27187. }
  27188. if (lightIndex > 0) {
  27189. lightFallbackRank = rank + lightIndex;
  27190. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  27191. }
  27192. if (!defines["SHADOWS"]) {
  27193. if (defines["SHADOW" + lightIndex]) {
  27194. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  27195. }
  27196. if (defines["SHADOWPCF" + lightIndex]) {
  27197. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  27198. }
  27199. if (defines["SHADOWESM" + lightIndex]) {
  27200. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  27201. }
  27202. }
  27203. }
  27204. return lightFallbackRank++;
  27205. };
  27206. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  27207. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  27208. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  27209. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  27210. var manager = mesh.morphTargetManager;
  27211. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  27212. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  27213. for (var index = 0; index < influencers; index++) {
  27214. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  27215. if (normal) {
  27216. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  27217. }
  27218. if (tangent) {
  27219. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  27220. }
  27221. if (attribs.length > maxAttributesCount) {
  27222. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  27223. }
  27224. }
  27225. }
  27226. };
  27227. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  27228. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  27229. fallbacks.addCPUSkinningFallback(0, mesh);
  27230. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27231. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27232. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  27233. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  27234. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  27235. }
  27236. }
  27237. };
  27238. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  27239. if (defines["INSTANCES"]) {
  27240. attribs.push("world0");
  27241. attribs.push("world1");
  27242. attribs.push("world2");
  27243. attribs.push("world3");
  27244. }
  27245. };
  27246. // Bindings
  27247. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  27248. if (light.shadowEnabled && mesh.receiveShadows) {
  27249. var shadowGenerator = light.getShadowGenerator();
  27250. if (shadowGenerator) {
  27251. shadowGenerator.bindShadowLight(lightIndex, effect);
  27252. }
  27253. }
  27254. };
  27255. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  27256. light.transferToEffect(effect, lightIndex + "");
  27257. };
  27258. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  27259. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  27260. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  27261. var lightIndex = 0;
  27262. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  27263. var light = _a[_i];
  27264. var scaledIntensity = light.getScaledIntensity();
  27265. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  27266. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  27267. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  27268. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  27269. if (defines["SPECULARTERM"]) {
  27270. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  27271. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  27272. }
  27273. // Shadows
  27274. if (scene.shadowsEnabled) {
  27275. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  27276. }
  27277. light._uniformBuffer.update();
  27278. lightIndex++;
  27279. if (lightIndex === maxSimultaneousLights)
  27280. break;
  27281. }
  27282. };
  27283. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  27284. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  27285. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  27286. effect.setColor3("vFogColor", scene.fogColor);
  27287. }
  27288. };
  27289. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  27290. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  27291. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  27292. if (matrices && effect) {
  27293. effect.setMatrices("mBones", matrices);
  27294. }
  27295. }
  27296. };
  27297. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  27298. var manager = abstractMesh.morphTargetManager;
  27299. if (!abstractMesh || !manager) {
  27300. return;
  27301. }
  27302. effect.setFloatArray("morphTargetInfluences", manager.influences);
  27303. };
  27304. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  27305. if (defines["LOGARITHMICDEPTH"]) {
  27306. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  27307. }
  27308. };
  27309. MaterialHelper.BindClipPlane = function (effect, scene) {
  27310. if (scene.clipPlane) {
  27311. var clipPlane = scene.clipPlane;
  27312. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  27313. }
  27314. };
  27315. return MaterialHelper;
  27316. }());
  27317. BABYLON.MaterialHelper = MaterialHelper;
  27318. })(BABYLON || (BABYLON = {}));
  27319. //# sourceMappingURL=babylon.materialHelper.js.map
  27320. var __assign = (this && this.__assign) || Object.assign || function(t) {
  27321. for (var s, i = 1, n = arguments.length; i < n; i++) {
  27322. s = arguments[i];
  27323. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  27324. t[p] = s[p];
  27325. }
  27326. return t;
  27327. };
  27328. var BABYLON;
  27329. (function (BABYLON) {
  27330. var MaterialDefines = /** @class */ (function () {
  27331. function MaterialDefines() {
  27332. this._isDirty = true;
  27333. this._areLightsDirty = true;
  27334. this._areAttributesDirty = true;
  27335. this._areTexturesDirty = true;
  27336. this._areFresnelDirty = true;
  27337. this._areMiscDirty = true;
  27338. this._areImageProcessingDirty = true;
  27339. this._normals = false;
  27340. this._uvs = false;
  27341. this._needNormals = false;
  27342. this._needUVs = false;
  27343. }
  27344. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  27345. get: function () {
  27346. return this._isDirty;
  27347. },
  27348. enumerable: true,
  27349. configurable: true
  27350. });
  27351. MaterialDefines.prototype.markAsProcessed = function () {
  27352. this._isDirty = false;
  27353. this._areAttributesDirty = false;
  27354. this._areTexturesDirty = false;
  27355. this._areFresnelDirty = false;
  27356. this._areLightsDirty = false;
  27357. this._areMiscDirty = false;
  27358. this._areImageProcessingDirty = false;
  27359. };
  27360. MaterialDefines.prototype.markAsUnprocessed = function () {
  27361. this._isDirty = true;
  27362. };
  27363. MaterialDefines.prototype.markAllAsDirty = function () {
  27364. this._areTexturesDirty = true;
  27365. this._areAttributesDirty = true;
  27366. this._areLightsDirty = true;
  27367. this._areFresnelDirty = true;
  27368. this._areMiscDirty = true;
  27369. this._areImageProcessingDirty = true;
  27370. this._isDirty = true;
  27371. };
  27372. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  27373. this._areImageProcessingDirty = true;
  27374. this._isDirty = true;
  27375. };
  27376. MaterialDefines.prototype.markAsLightDirty = function () {
  27377. this._areLightsDirty = true;
  27378. this._isDirty = true;
  27379. };
  27380. MaterialDefines.prototype.markAsAttributesDirty = function () {
  27381. this._areAttributesDirty = true;
  27382. this._isDirty = true;
  27383. };
  27384. MaterialDefines.prototype.markAsTexturesDirty = function () {
  27385. this._areTexturesDirty = true;
  27386. this._isDirty = true;
  27387. };
  27388. MaterialDefines.prototype.markAsFresnelDirty = function () {
  27389. this._areFresnelDirty = true;
  27390. this._isDirty = true;
  27391. };
  27392. MaterialDefines.prototype.markAsMiscDirty = function () {
  27393. this._areMiscDirty = true;
  27394. this._isDirty = true;
  27395. };
  27396. MaterialDefines.prototype.rebuild = function () {
  27397. if (this._keys) {
  27398. delete this._keys;
  27399. }
  27400. this._keys = [];
  27401. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  27402. var key = _a[_i];
  27403. if (key[0] === "_") {
  27404. continue;
  27405. }
  27406. this._keys.push(key);
  27407. }
  27408. };
  27409. MaterialDefines.prototype.isEqual = function (other) {
  27410. if (this._keys.length !== other._keys.length) {
  27411. return false;
  27412. }
  27413. for (var index = 0; index < this._keys.length; index++) {
  27414. var prop = this._keys[index];
  27415. if (this[prop] !== other[prop]) {
  27416. return false;
  27417. }
  27418. }
  27419. return true;
  27420. };
  27421. MaterialDefines.prototype.cloneTo = function (other) {
  27422. if (this._keys.length !== other._keys.length) {
  27423. other._keys = this._keys.slice(0);
  27424. }
  27425. for (var index = 0; index < this._keys.length; index++) {
  27426. var prop = this._keys[index];
  27427. other[prop] = this[prop];
  27428. }
  27429. };
  27430. MaterialDefines.prototype.reset = function () {
  27431. for (var index = 0; index < this._keys.length; index++) {
  27432. var prop = this._keys[index];
  27433. if (typeof (this[prop]) === "number") {
  27434. this[prop] = 0;
  27435. }
  27436. else {
  27437. this[prop] = false;
  27438. }
  27439. }
  27440. };
  27441. MaterialDefines.prototype.toString = function () {
  27442. var result = "";
  27443. for (var index = 0; index < this._keys.length; index++) {
  27444. var prop = this._keys[index];
  27445. var value = this[prop];
  27446. if (typeof (value) === "number") {
  27447. result += "#define " + prop + " " + this[prop] + "\n";
  27448. }
  27449. else if (value) {
  27450. result += "#define " + prop + "\n";
  27451. }
  27452. }
  27453. return result;
  27454. };
  27455. return MaterialDefines;
  27456. }());
  27457. BABYLON.MaterialDefines = MaterialDefines;
  27458. var Material = /** @class */ (function () {
  27459. function Material(name, scene, doNotAdd) {
  27460. this.checkReadyOnEveryCall = false;
  27461. this.checkReadyOnlyOnce = false;
  27462. this.state = "";
  27463. this.alpha = 1.0;
  27464. this._backFaceCulling = true;
  27465. this.doNotSerialize = false;
  27466. this.storeEffectOnSubMeshes = false;
  27467. /**
  27468. * An event triggered when the material is disposed.
  27469. * @type {BABYLON.Observable}
  27470. */
  27471. this.onDisposeObservable = new BABYLON.Observable();
  27472. /**
  27473. * An event triggered when the material is bound.
  27474. * @type {BABYLON.Observable}
  27475. */
  27476. this.onBindObservable = new BABYLON.Observable();
  27477. /**
  27478. * An event triggered when the material is unbound.
  27479. * @type {BABYLON.Observable}
  27480. */
  27481. this.onUnBindObservable = new BABYLON.Observable();
  27482. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  27483. this._needDepthPrePass = false;
  27484. this.disableDepthWrite = false;
  27485. this.forceDepthWrite = false;
  27486. this.separateCullingPass = false;
  27487. this._fogEnabled = true;
  27488. this.pointSize = 1.0;
  27489. this.zOffset = 0;
  27490. this._wasPreviouslyReady = false;
  27491. this._fillMode = Material.TriangleFillMode;
  27492. this.name = name;
  27493. this.id = name || BABYLON.Tools.RandomId();
  27494. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  27495. if (this._scene.useRightHandedSystem) {
  27496. this.sideOrientation = Material.ClockWiseSideOrientation;
  27497. }
  27498. else {
  27499. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  27500. }
  27501. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  27502. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  27503. if (!doNotAdd) {
  27504. this._scene.materials.push(this);
  27505. }
  27506. }
  27507. Object.defineProperty(Material, "TriangleFillMode", {
  27508. get: function () {
  27509. return Material._TriangleFillMode;
  27510. },
  27511. enumerable: true,
  27512. configurable: true
  27513. });
  27514. Object.defineProperty(Material, "WireFrameFillMode", {
  27515. get: function () {
  27516. return Material._WireFrameFillMode;
  27517. },
  27518. enumerable: true,
  27519. configurable: true
  27520. });
  27521. Object.defineProperty(Material, "PointFillMode", {
  27522. get: function () {
  27523. return Material._PointFillMode;
  27524. },
  27525. enumerable: true,
  27526. configurable: true
  27527. });
  27528. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  27529. get: function () {
  27530. return Material._ClockWiseSideOrientation;
  27531. },
  27532. enumerable: true,
  27533. configurable: true
  27534. });
  27535. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  27536. get: function () {
  27537. return Material._CounterClockWiseSideOrientation;
  27538. },
  27539. enumerable: true,
  27540. configurable: true
  27541. });
  27542. Object.defineProperty(Material, "TextureDirtyFlag", {
  27543. get: function () {
  27544. return Material._TextureDirtyFlag;
  27545. },
  27546. enumerable: true,
  27547. configurable: true
  27548. });
  27549. Object.defineProperty(Material, "LightDirtyFlag", {
  27550. get: function () {
  27551. return Material._LightDirtyFlag;
  27552. },
  27553. enumerable: true,
  27554. configurable: true
  27555. });
  27556. Object.defineProperty(Material, "FresnelDirtyFlag", {
  27557. get: function () {
  27558. return Material._FresnelDirtyFlag;
  27559. },
  27560. enumerable: true,
  27561. configurable: true
  27562. });
  27563. Object.defineProperty(Material, "AttributesDirtyFlag", {
  27564. get: function () {
  27565. return Material._AttributesDirtyFlag;
  27566. },
  27567. enumerable: true,
  27568. configurable: true
  27569. });
  27570. Object.defineProperty(Material, "MiscDirtyFlag", {
  27571. get: function () {
  27572. return Material._MiscDirtyFlag;
  27573. },
  27574. enumerable: true,
  27575. configurable: true
  27576. });
  27577. Object.defineProperty(Material.prototype, "backFaceCulling", {
  27578. get: function () {
  27579. return this._backFaceCulling;
  27580. },
  27581. set: function (value) {
  27582. if (this._backFaceCulling === value) {
  27583. return;
  27584. }
  27585. this._backFaceCulling = value;
  27586. this.markAsDirty(Material.TextureDirtyFlag);
  27587. },
  27588. enumerable: true,
  27589. configurable: true
  27590. });
  27591. Object.defineProperty(Material.prototype, "onDispose", {
  27592. set: function (callback) {
  27593. if (this._onDisposeObserver) {
  27594. this.onDisposeObservable.remove(this._onDisposeObserver);
  27595. }
  27596. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27597. },
  27598. enumerable: true,
  27599. configurable: true
  27600. });
  27601. Object.defineProperty(Material.prototype, "onBind", {
  27602. set: function (callback) {
  27603. if (this._onBindObserver) {
  27604. this.onBindObservable.remove(this._onBindObserver);
  27605. }
  27606. this._onBindObserver = this.onBindObservable.add(callback);
  27607. },
  27608. enumerable: true,
  27609. configurable: true
  27610. });
  27611. Object.defineProperty(Material.prototype, "alphaMode", {
  27612. get: function () {
  27613. return this._alphaMode;
  27614. },
  27615. set: function (value) {
  27616. if (this._alphaMode === value) {
  27617. return;
  27618. }
  27619. this._alphaMode = value;
  27620. this.markAsDirty(Material.TextureDirtyFlag);
  27621. },
  27622. enumerable: true,
  27623. configurable: true
  27624. });
  27625. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  27626. get: function () {
  27627. return this._needDepthPrePass;
  27628. },
  27629. set: function (value) {
  27630. if (this._needDepthPrePass === value) {
  27631. return;
  27632. }
  27633. this._needDepthPrePass = value;
  27634. if (this._needDepthPrePass) {
  27635. this.checkReadyOnEveryCall = true;
  27636. }
  27637. },
  27638. enumerable: true,
  27639. configurable: true
  27640. });
  27641. Object.defineProperty(Material.prototype, "fogEnabled", {
  27642. get: function () {
  27643. return this._fogEnabled;
  27644. },
  27645. set: function (value) {
  27646. if (this._fogEnabled === value) {
  27647. return;
  27648. }
  27649. this._fogEnabled = value;
  27650. this.markAsDirty(Material.MiscDirtyFlag);
  27651. },
  27652. enumerable: true,
  27653. configurable: true
  27654. });
  27655. Object.defineProperty(Material.prototype, "wireframe", {
  27656. get: function () {
  27657. return this._fillMode === Material.WireFrameFillMode;
  27658. },
  27659. set: function (value) {
  27660. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  27661. },
  27662. enumerable: true,
  27663. configurable: true
  27664. });
  27665. Object.defineProperty(Material.prototype, "pointsCloud", {
  27666. get: function () {
  27667. return this._fillMode === Material.PointFillMode;
  27668. },
  27669. set: function (value) {
  27670. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  27671. },
  27672. enumerable: true,
  27673. configurable: true
  27674. });
  27675. Object.defineProperty(Material.prototype, "fillMode", {
  27676. get: function () {
  27677. return this._fillMode;
  27678. },
  27679. set: function (value) {
  27680. if (this._fillMode === value) {
  27681. return;
  27682. }
  27683. this._fillMode = value;
  27684. this.markAsDirty(Material.MiscDirtyFlag);
  27685. },
  27686. enumerable: true,
  27687. configurable: true
  27688. });
  27689. /**
  27690. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27691. * subclasses should override adding information pertainent to themselves
  27692. */
  27693. Material.prototype.toString = function (fullDetails) {
  27694. var ret = "Name: " + this.name;
  27695. if (fullDetails) {
  27696. }
  27697. return ret;
  27698. };
  27699. /**
  27700. * Child classes can use it to update shaders
  27701. */
  27702. Material.prototype.getClassName = function () {
  27703. return "Material";
  27704. };
  27705. Object.defineProperty(Material.prototype, "isFrozen", {
  27706. get: function () {
  27707. return this.checkReadyOnlyOnce;
  27708. },
  27709. enumerable: true,
  27710. configurable: true
  27711. });
  27712. Material.prototype.freeze = function () {
  27713. this.checkReadyOnlyOnce = true;
  27714. };
  27715. Material.prototype.unfreeze = function () {
  27716. this.checkReadyOnlyOnce = false;
  27717. };
  27718. Material.prototype.isReady = function (mesh, useInstances) {
  27719. return true;
  27720. };
  27721. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  27722. return false;
  27723. };
  27724. Material.prototype.getEffect = function () {
  27725. return this._effect;
  27726. };
  27727. Material.prototype.getScene = function () {
  27728. return this._scene;
  27729. };
  27730. Material.prototype.needAlphaBlending = function () {
  27731. return (this.alpha < 1.0);
  27732. };
  27733. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  27734. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  27735. };
  27736. Material.prototype.needAlphaTesting = function () {
  27737. return false;
  27738. };
  27739. Material.prototype.getAlphaTestTexture = function () {
  27740. return null;
  27741. };
  27742. Material.prototype.markDirty = function () {
  27743. this._wasPreviouslyReady = false;
  27744. };
  27745. Material.prototype._preBind = function (effect, overrideOrientation) {
  27746. if (overrideOrientation === void 0) { overrideOrientation = null; }
  27747. var engine = this._scene.getEngine();
  27748. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  27749. var reverse = orientation === Material.ClockWiseSideOrientation;
  27750. engine.enableEffect(effect ? effect : this._effect);
  27751. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  27752. return reverse;
  27753. };
  27754. Material.prototype.bind = function (world, mesh) {
  27755. };
  27756. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  27757. };
  27758. Material.prototype.bindOnlyWorldMatrix = function (world) {
  27759. };
  27760. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  27761. sceneUbo.bindToEffect(effect, "Scene");
  27762. };
  27763. Material.prototype.bindView = function (effect) {
  27764. if (!this._useUBO) {
  27765. effect.setMatrix("view", this.getScene().getViewMatrix());
  27766. }
  27767. else {
  27768. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27769. }
  27770. };
  27771. Material.prototype.bindViewProjection = function (effect) {
  27772. if (!this._useUBO) {
  27773. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  27774. }
  27775. else {
  27776. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27777. }
  27778. };
  27779. Material.prototype._afterBind = function (mesh) {
  27780. this._scene._cachedMaterial = this;
  27781. if (mesh) {
  27782. this._scene._cachedVisibility = mesh.visibility;
  27783. }
  27784. else {
  27785. this._scene._cachedVisibility = 1;
  27786. }
  27787. if (mesh) {
  27788. this.onBindObservable.notifyObservers(mesh);
  27789. }
  27790. if (this.disableDepthWrite) {
  27791. var engine = this._scene.getEngine();
  27792. this._cachedDepthWriteState = engine.getDepthWrite();
  27793. engine.setDepthWrite(false);
  27794. }
  27795. };
  27796. Material.prototype.unbind = function () {
  27797. this.onUnBindObservable.notifyObservers(this);
  27798. if (this.disableDepthWrite) {
  27799. var engine = this._scene.getEngine();
  27800. engine.setDepthWrite(this._cachedDepthWriteState);
  27801. }
  27802. };
  27803. Material.prototype.getActiveTextures = function () {
  27804. return [];
  27805. };
  27806. Material.prototype.hasTexture = function (texture) {
  27807. return false;
  27808. };
  27809. Material.prototype.clone = function (name) {
  27810. return null;
  27811. };
  27812. Material.prototype.getBindedMeshes = function () {
  27813. var result = new Array();
  27814. for (var index = 0; index < this._scene.meshes.length; index++) {
  27815. var mesh = this._scene.meshes[index];
  27816. if (mesh.material === this) {
  27817. result.push(mesh);
  27818. }
  27819. }
  27820. return result;
  27821. };
  27822. /**
  27823. * Force shader compilation including textures ready check
  27824. */
  27825. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  27826. var _this = this;
  27827. var localOptions = __assign({ alphaTest: null, clipPlane: false }, options);
  27828. var subMesh = new BABYLON.BaseSubMesh();
  27829. var scene = this.getScene();
  27830. var engine = scene.getEngine();
  27831. var checkReady = function () {
  27832. if (!_this._scene || !_this._scene.getEngine()) {
  27833. return;
  27834. }
  27835. if (subMesh._materialDefines) {
  27836. subMesh._materialDefines._renderId = -1;
  27837. }
  27838. var alphaTestState = engine.getAlphaTesting();
  27839. var clipPlaneState = scene.clipPlane;
  27840. engine.setAlphaTesting(localOptions.alphaTest || (!_this.needAlphaBlendingForMesh(mesh) && _this.needAlphaTesting()));
  27841. if (localOptions.clipPlane) {
  27842. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  27843. }
  27844. if (_this.storeEffectOnSubMeshes) {
  27845. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  27846. if (onCompiled) {
  27847. onCompiled(_this);
  27848. }
  27849. }
  27850. else {
  27851. setTimeout(checkReady, 16);
  27852. }
  27853. }
  27854. else {
  27855. if (_this.isReady(mesh)) {
  27856. if (onCompiled) {
  27857. onCompiled(_this);
  27858. }
  27859. }
  27860. else {
  27861. setTimeout(checkReady, 16);
  27862. }
  27863. }
  27864. engine.setAlphaTesting(alphaTestState);
  27865. if (options && options.clipPlane) {
  27866. scene.clipPlane = clipPlaneState;
  27867. }
  27868. };
  27869. checkReady();
  27870. };
  27871. Material.prototype.markAsDirty = function (flag) {
  27872. if (flag & Material.TextureDirtyFlag) {
  27873. this._markAllSubMeshesAsTexturesDirty();
  27874. }
  27875. if (flag & Material.LightDirtyFlag) {
  27876. this._markAllSubMeshesAsLightsDirty();
  27877. }
  27878. if (flag & Material.FresnelDirtyFlag) {
  27879. this._markAllSubMeshesAsFresnelDirty();
  27880. }
  27881. if (flag & Material.AttributesDirtyFlag) {
  27882. this._markAllSubMeshesAsAttributesDirty();
  27883. }
  27884. if (flag & Material.MiscDirtyFlag) {
  27885. this._markAllSubMeshesAsMiscDirty();
  27886. }
  27887. this.getScene().resetCachedMaterial();
  27888. };
  27889. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  27890. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  27891. var mesh = _a[_i];
  27892. if (!mesh.subMeshes) {
  27893. continue;
  27894. }
  27895. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  27896. var subMesh = _c[_b];
  27897. if (subMesh.getMaterial() !== this) {
  27898. continue;
  27899. }
  27900. if (!subMesh._materialDefines) {
  27901. continue;
  27902. }
  27903. func(subMesh._materialDefines);
  27904. }
  27905. }
  27906. };
  27907. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  27908. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  27909. };
  27910. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  27911. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  27912. };
  27913. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  27914. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  27915. };
  27916. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  27917. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  27918. };
  27919. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  27920. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  27921. };
  27922. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  27923. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  27924. };
  27925. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27926. // Animations
  27927. this.getScene().stopAnimation(this);
  27928. // Remove from scene
  27929. var index = this._scene.materials.indexOf(this);
  27930. if (index >= 0) {
  27931. this._scene.materials.splice(index, 1);
  27932. }
  27933. // Remove from meshes
  27934. for (index = 0; index < this._scene.meshes.length; index++) {
  27935. var mesh = this._scene.meshes[index];
  27936. if (mesh.material === this) {
  27937. mesh.material = null;
  27938. if (mesh.geometry) {
  27939. var geometry = (mesh.geometry);
  27940. if (this.storeEffectOnSubMeshes) {
  27941. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  27942. var subMesh = _a[_i];
  27943. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  27944. if (forceDisposeEffect && subMesh._materialEffect) {
  27945. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  27946. }
  27947. }
  27948. }
  27949. else {
  27950. geometry._releaseVertexArrayObject(this._effect);
  27951. }
  27952. }
  27953. }
  27954. }
  27955. this._uniformBuffer.dispose();
  27956. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  27957. if (forceDisposeEffect && this._effect) {
  27958. if (!this.storeEffectOnSubMeshes) {
  27959. this._scene.getEngine()._releaseEffect(this._effect);
  27960. }
  27961. this._effect = null;
  27962. }
  27963. // Callback
  27964. this.onDisposeObservable.notifyObservers(this);
  27965. this.onDisposeObservable.clear();
  27966. this.onBindObservable.clear();
  27967. this.onUnBindObservable.clear();
  27968. };
  27969. Material.prototype.serialize = function () {
  27970. return BABYLON.SerializationHelper.Serialize(this);
  27971. };
  27972. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  27973. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  27974. multiMaterial.id = parsedMultiMaterial.id;
  27975. if (BABYLON.Tags) {
  27976. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  27977. }
  27978. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  27979. var subMatId = parsedMultiMaterial.materials[matIndex];
  27980. if (subMatId) {
  27981. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  27982. }
  27983. else {
  27984. multiMaterial.subMaterials.push(null);
  27985. }
  27986. }
  27987. return multiMaterial;
  27988. };
  27989. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  27990. if (!parsedMaterial.customType) {
  27991. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  27992. }
  27993. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  27994. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  27995. if (!BABYLON.LegacyPBRMaterial) {
  27996. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  27997. return;
  27998. }
  27999. }
  28000. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  28001. return materialType.Parse(parsedMaterial, scene, rootUrl);
  28002. ;
  28003. };
  28004. Material._TriangleFillMode = 0;
  28005. Material._WireFrameFillMode = 1;
  28006. Material._PointFillMode = 2;
  28007. Material._ClockWiseSideOrientation = 0;
  28008. Material._CounterClockWiseSideOrientation = 1;
  28009. Material._TextureDirtyFlag = 1;
  28010. Material._LightDirtyFlag = 2;
  28011. Material._FresnelDirtyFlag = 4;
  28012. Material._AttributesDirtyFlag = 8;
  28013. Material._MiscDirtyFlag = 16;
  28014. __decorate([
  28015. BABYLON.serialize()
  28016. ], Material.prototype, "id", void 0);
  28017. __decorate([
  28018. BABYLON.serialize()
  28019. ], Material.prototype, "name", void 0);
  28020. __decorate([
  28021. BABYLON.serialize()
  28022. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  28023. __decorate([
  28024. BABYLON.serialize()
  28025. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  28026. __decorate([
  28027. BABYLON.serialize()
  28028. ], Material.prototype, "state", void 0);
  28029. __decorate([
  28030. BABYLON.serialize()
  28031. ], Material.prototype, "alpha", void 0);
  28032. __decorate([
  28033. BABYLON.serialize("backFaceCulling")
  28034. ], Material.prototype, "_backFaceCulling", void 0);
  28035. __decorate([
  28036. BABYLON.serialize()
  28037. ], Material.prototype, "sideOrientation", void 0);
  28038. __decorate([
  28039. BABYLON.serialize("alphaMode")
  28040. ], Material.prototype, "_alphaMode", void 0);
  28041. __decorate([
  28042. BABYLON.serialize()
  28043. ], Material.prototype, "_needDepthPrePass", void 0);
  28044. __decorate([
  28045. BABYLON.serialize()
  28046. ], Material.prototype, "disableDepthWrite", void 0);
  28047. __decorate([
  28048. BABYLON.serialize()
  28049. ], Material.prototype, "forceDepthWrite", void 0);
  28050. __decorate([
  28051. BABYLON.serialize()
  28052. ], Material.prototype, "separateCullingPass", void 0);
  28053. __decorate([
  28054. BABYLON.serialize("fogEnabled")
  28055. ], Material.prototype, "_fogEnabled", void 0);
  28056. __decorate([
  28057. BABYLON.serialize()
  28058. ], Material.prototype, "pointSize", void 0);
  28059. __decorate([
  28060. BABYLON.serialize()
  28061. ], Material.prototype, "zOffset", void 0);
  28062. __decorate([
  28063. BABYLON.serialize()
  28064. ], Material.prototype, "wireframe", null);
  28065. __decorate([
  28066. BABYLON.serialize()
  28067. ], Material.prototype, "pointsCloud", null);
  28068. __decorate([
  28069. BABYLON.serialize()
  28070. ], Material.prototype, "fillMode", null);
  28071. return Material;
  28072. }());
  28073. BABYLON.Material = Material;
  28074. })(BABYLON || (BABYLON = {}));
  28075. //# sourceMappingURL=babylon.material.js.map
  28076. var BABYLON;
  28077. (function (BABYLON) {
  28078. var UniformBuffer = /** @class */ (function () {
  28079. /**
  28080. * Uniform buffer objects.
  28081. *
  28082. * Handles blocks of uniform on the GPU.
  28083. *
  28084. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  28085. *
  28086. * For more information, please refer to :
  28087. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  28088. */
  28089. function UniformBuffer(engine, data, dynamic) {
  28090. this._engine = engine;
  28091. this._noUBO = !engine.supportsUniformBuffers;
  28092. this._dynamic = dynamic;
  28093. this._data = data || [];
  28094. this._uniformLocations = {};
  28095. this._uniformSizes = {};
  28096. this._uniformLocationPointer = 0;
  28097. this._needSync = false;
  28098. if (this._noUBO) {
  28099. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  28100. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  28101. this.updateFloat = this._updateFloatForEffect;
  28102. this.updateFloat2 = this._updateFloat2ForEffect;
  28103. this.updateFloat3 = this._updateFloat3ForEffect;
  28104. this.updateFloat4 = this._updateFloat4ForEffect;
  28105. this.updateMatrix = this._updateMatrixForEffect;
  28106. this.updateVector3 = this._updateVector3ForEffect;
  28107. this.updateVector4 = this._updateVector4ForEffect;
  28108. this.updateColor3 = this._updateColor3ForEffect;
  28109. this.updateColor4 = this._updateColor4ForEffect;
  28110. }
  28111. else {
  28112. this._engine._uniformBuffers.push(this);
  28113. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  28114. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  28115. this.updateFloat = this._updateFloatForUniform;
  28116. this.updateFloat2 = this._updateFloat2ForUniform;
  28117. this.updateFloat3 = this._updateFloat3ForUniform;
  28118. this.updateFloat4 = this._updateFloat4ForUniform;
  28119. this.updateMatrix = this._updateMatrixForUniform;
  28120. this.updateVector3 = this._updateVector3ForUniform;
  28121. this.updateVector4 = this._updateVector4ForUniform;
  28122. this.updateColor3 = this._updateColor3ForUniform;
  28123. this.updateColor4 = this._updateColor4ForUniform;
  28124. }
  28125. }
  28126. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  28127. // Properties
  28128. /**
  28129. * Indicates if the buffer is using the WebGL2 UBO implementation,
  28130. * or just falling back on setUniformXXX calls.
  28131. */
  28132. get: function () {
  28133. return !this._noUBO;
  28134. },
  28135. enumerable: true,
  28136. configurable: true
  28137. });
  28138. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  28139. /**
  28140. * Indicates if the WebGL underlying uniform buffer is in sync
  28141. * with the javascript cache data.
  28142. */
  28143. get: function () {
  28144. return !this._needSync;
  28145. },
  28146. enumerable: true,
  28147. configurable: true
  28148. });
  28149. /**
  28150. * Indicates if the WebGL underlying uniform buffer is dynamic.
  28151. * Also, a dynamic UniformBuffer will disable cache verification and always
  28152. * update the underlying WebGL uniform buffer to the GPU.
  28153. */
  28154. UniformBuffer.prototype.isDynamic = function () {
  28155. return this._dynamic !== undefined;
  28156. };
  28157. /**
  28158. * The data cache on JS side.
  28159. */
  28160. UniformBuffer.prototype.getData = function () {
  28161. return this._bufferData;
  28162. };
  28163. /**
  28164. * The underlying WebGL Uniform buffer.
  28165. */
  28166. UniformBuffer.prototype.getBuffer = function () {
  28167. return this._buffer;
  28168. };
  28169. /**
  28170. * std140 layout specifies how to align data within an UBO structure.
  28171. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  28172. * for specs.
  28173. */
  28174. UniformBuffer.prototype._fillAlignment = function (size) {
  28175. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  28176. // and 4x4 matrices
  28177. // TODO : change if other types are used
  28178. var alignment;
  28179. if (size <= 2) {
  28180. alignment = size;
  28181. }
  28182. else {
  28183. alignment = 4;
  28184. }
  28185. if ((this._uniformLocationPointer % alignment) !== 0) {
  28186. var oldPointer = this._uniformLocationPointer;
  28187. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  28188. var diff = this._uniformLocationPointer - oldPointer;
  28189. for (var i = 0; i < diff; i++) {
  28190. this._data.push(0);
  28191. }
  28192. }
  28193. };
  28194. /**
  28195. * Adds an uniform in the buffer.
  28196. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  28197. * for the layout to be correct !
  28198. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28199. * @param {number|number[]} size Data size, or data directly.
  28200. */
  28201. UniformBuffer.prototype.addUniform = function (name, size) {
  28202. if (this._noUBO) {
  28203. return;
  28204. }
  28205. if (this._uniformLocations[name] !== undefined) {
  28206. // Already existing uniform
  28207. return;
  28208. }
  28209. // This function must be called in the order of the shader layout !
  28210. // size can be the size of the uniform, or data directly
  28211. var data;
  28212. if (size instanceof Array) {
  28213. data = size;
  28214. size = data.length;
  28215. }
  28216. else {
  28217. size = size;
  28218. data = [];
  28219. // Fill with zeros
  28220. for (var i = 0; i < size; i++) {
  28221. data.push(0);
  28222. }
  28223. }
  28224. this._fillAlignment(size);
  28225. this._uniformSizes[name] = size;
  28226. this._uniformLocations[name] = this._uniformLocationPointer;
  28227. this._uniformLocationPointer += size;
  28228. for (var i = 0; i < size; i++) {
  28229. this._data.push(data[i]);
  28230. }
  28231. this._needSync = true;
  28232. };
  28233. /**
  28234. * Wrapper for addUniform.
  28235. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28236. * @param {Matrix} mat A 4x4 matrix.
  28237. */
  28238. UniformBuffer.prototype.addMatrix = function (name, mat) {
  28239. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  28240. };
  28241. /**
  28242. * Wrapper for addUniform.
  28243. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28244. * @param {number} x
  28245. * @param {number} y
  28246. */
  28247. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  28248. var temp = [x, y];
  28249. this.addUniform(name, temp);
  28250. };
  28251. /**
  28252. * Wrapper for addUniform.
  28253. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28254. * @param {number} x
  28255. * @param {number} y
  28256. * @param {number} z
  28257. */
  28258. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  28259. var temp = [x, y, z];
  28260. this.addUniform(name, temp);
  28261. };
  28262. /**
  28263. * Wrapper for addUniform.
  28264. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28265. * @param {Color3} color
  28266. */
  28267. UniformBuffer.prototype.addColor3 = function (name, color) {
  28268. var temp = new Array();
  28269. color.toArray(temp);
  28270. this.addUniform(name, temp);
  28271. };
  28272. /**
  28273. * Wrapper for addUniform.
  28274. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28275. * @param {Color3} color
  28276. * @param {number} alpha
  28277. */
  28278. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  28279. var temp = new Array();
  28280. color.toArray(temp);
  28281. temp.push(alpha);
  28282. this.addUniform(name, temp);
  28283. };
  28284. /**
  28285. * Wrapper for addUniform.
  28286. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28287. * @param {Vector3} vector
  28288. */
  28289. UniformBuffer.prototype.addVector3 = function (name, vector) {
  28290. var temp = new Array();
  28291. vector.toArray(temp);
  28292. this.addUniform(name, temp);
  28293. };
  28294. /**
  28295. * Wrapper for addUniform.
  28296. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28297. */
  28298. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  28299. this.addUniform(name, 12);
  28300. };
  28301. /**
  28302. * Wrapper for addUniform.
  28303. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28304. */
  28305. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  28306. this.addUniform(name, 8);
  28307. };
  28308. /**
  28309. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  28310. */
  28311. UniformBuffer.prototype.create = function () {
  28312. if (this._noUBO) {
  28313. return;
  28314. }
  28315. if (this._buffer) {
  28316. return; // nothing to do
  28317. }
  28318. // See spec, alignment must be filled as a vec4
  28319. this._fillAlignment(4);
  28320. this._bufferData = new Float32Array(this._data);
  28321. this._rebuild();
  28322. this._needSync = true;
  28323. };
  28324. UniformBuffer.prototype._rebuild = function () {
  28325. if (this._noUBO) {
  28326. return;
  28327. }
  28328. if (this._dynamic) {
  28329. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  28330. }
  28331. else {
  28332. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  28333. }
  28334. };
  28335. /**
  28336. * Updates the WebGL Uniform Buffer on the GPU.
  28337. * If the `dynamic` flag is set to true, no cache comparison is done.
  28338. * Otherwise, the buffer will be updated only if the cache differs.
  28339. */
  28340. UniformBuffer.prototype.update = function () {
  28341. if (!this._buffer) {
  28342. this.create();
  28343. return;
  28344. }
  28345. if (!this._dynamic && !this._needSync) {
  28346. return;
  28347. }
  28348. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  28349. this._needSync = false;
  28350. };
  28351. /**
  28352. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  28353. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28354. * @param {number[]|Float32Array} data Flattened data
  28355. * @param {number} size Size of the data.
  28356. */
  28357. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  28358. var location = this._uniformLocations[uniformName];
  28359. if (location === undefined) {
  28360. if (this._buffer) {
  28361. // Cannot add an uniform if the buffer is already created
  28362. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  28363. return;
  28364. }
  28365. this.addUniform(uniformName, size);
  28366. location = this._uniformLocations[uniformName];
  28367. }
  28368. if (!this._buffer) {
  28369. this.create();
  28370. }
  28371. if (!this._dynamic) {
  28372. // Cache for static uniform buffers
  28373. var changed = false;
  28374. for (var i = 0; i < size; i++) {
  28375. if (this._bufferData[location + i] !== data[i]) {
  28376. changed = true;
  28377. this._bufferData[location + i] = data[i];
  28378. }
  28379. }
  28380. this._needSync = this._needSync || changed;
  28381. }
  28382. else {
  28383. // No cache for dynamic
  28384. for (var i = 0; i < size; i++) {
  28385. this._bufferData[location + i] = data[i];
  28386. }
  28387. }
  28388. };
  28389. // Update methods
  28390. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  28391. // To match std140, matrix must be realigned
  28392. for (var i = 0; i < 3; i++) {
  28393. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  28394. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  28395. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  28396. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28397. }
  28398. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  28399. };
  28400. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  28401. this._currentEffect.setMatrix3x3(name, matrix);
  28402. };
  28403. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  28404. this._currentEffect.setMatrix2x2(name, matrix);
  28405. };
  28406. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  28407. // To match std140, matrix must be realigned
  28408. for (var i = 0; i < 2; i++) {
  28409. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  28410. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  28411. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  28412. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28413. }
  28414. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  28415. };
  28416. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  28417. this._currentEffect.setFloat(name, x);
  28418. };
  28419. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  28420. UniformBuffer._tempBuffer[0] = x;
  28421. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  28422. };
  28423. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  28424. if (suffix === void 0) { suffix = ""; }
  28425. this._currentEffect.setFloat2(name + suffix, x, y);
  28426. };
  28427. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  28428. if (suffix === void 0) { suffix = ""; }
  28429. UniformBuffer._tempBuffer[0] = x;
  28430. UniformBuffer._tempBuffer[1] = y;
  28431. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  28432. };
  28433. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  28434. if (suffix === void 0) { suffix = ""; }
  28435. this._currentEffect.setFloat3(name + suffix, x, y, z);
  28436. };
  28437. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  28438. if (suffix === void 0) { suffix = ""; }
  28439. UniformBuffer._tempBuffer[0] = x;
  28440. UniformBuffer._tempBuffer[1] = y;
  28441. UniformBuffer._tempBuffer[2] = z;
  28442. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28443. };
  28444. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  28445. if (suffix === void 0) { suffix = ""; }
  28446. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  28447. };
  28448. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  28449. if (suffix === void 0) { suffix = ""; }
  28450. UniformBuffer._tempBuffer[0] = x;
  28451. UniformBuffer._tempBuffer[1] = y;
  28452. UniformBuffer._tempBuffer[2] = z;
  28453. UniformBuffer._tempBuffer[3] = w;
  28454. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28455. };
  28456. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  28457. this._currentEffect.setMatrix(name, mat);
  28458. };
  28459. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  28460. this.updateUniform(name, mat.toArray(), 16);
  28461. };
  28462. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  28463. this._currentEffect.setVector3(name, vector);
  28464. };
  28465. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  28466. vector.toArray(UniformBuffer._tempBuffer);
  28467. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28468. };
  28469. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  28470. this._currentEffect.setVector4(name, vector);
  28471. };
  28472. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  28473. vector.toArray(UniformBuffer._tempBuffer);
  28474. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28475. };
  28476. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  28477. if (suffix === void 0) { suffix = ""; }
  28478. this._currentEffect.setColor3(name + suffix, color);
  28479. };
  28480. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  28481. if (suffix === void 0) { suffix = ""; }
  28482. color.toArray(UniformBuffer._tempBuffer);
  28483. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28484. };
  28485. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  28486. if (suffix === void 0) { suffix = ""; }
  28487. this._currentEffect.setColor4(name + suffix, color, alpha);
  28488. };
  28489. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  28490. if (suffix === void 0) { suffix = ""; }
  28491. color.toArray(UniformBuffer._tempBuffer);
  28492. UniformBuffer._tempBuffer[3] = alpha;
  28493. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28494. };
  28495. /**
  28496. * Sets a sampler uniform on the effect.
  28497. * @param {string} name Name of the sampler.
  28498. * @param {Texture} texture
  28499. */
  28500. UniformBuffer.prototype.setTexture = function (name, texture) {
  28501. this._currentEffect.setTexture(name, texture);
  28502. };
  28503. /**
  28504. * Directly updates the value of the uniform in the cache AND on the GPU.
  28505. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28506. * @param {number[]|Float32Array} data Flattened data
  28507. */
  28508. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  28509. this.updateUniform(uniformName, data, data.length);
  28510. this.update();
  28511. };
  28512. /**
  28513. * Binds this uniform buffer to an effect.
  28514. * @param {Effect} effect
  28515. * @param {string} name Name of the uniform block in the shader.
  28516. */
  28517. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  28518. this._currentEffect = effect;
  28519. if (this._noUBO || !this._buffer) {
  28520. return;
  28521. }
  28522. effect.bindUniformBuffer(this._buffer, name);
  28523. };
  28524. /**
  28525. * Disposes the uniform buffer.
  28526. */
  28527. UniformBuffer.prototype.dispose = function () {
  28528. if (this._noUBO) {
  28529. return;
  28530. }
  28531. var index = this._engine._uniformBuffers.indexOf(this);
  28532. if (index !== -1) {
  28533. this._engine._uniformBuffers.splice(index, 1);
  28534. }
  28535. if (!this._buffer) {
  28536. return;
  28537. }
  28538. if (this._engine._releaseBuffer(this._buffer)) {
  28539. this._buffer = null;
  28540. }
  28541. };
  28542. // Pool for avoiding memory leaks
  28543. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  28544. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  28545. return UniformBuffer;
  28546. }());
  28547. BABYLON.UniformBuffer = UniformBuffer;
  28548. })(BABYLON || (BABYLON = {}));
  28549. //# sourceMappingURL=babylon.uniformBuffer.js.map
  28550. var BABYLON;
  28551. (function (BABYLON) {
  28552. var PushMaterial = /** @class */ (function (_super) {
  28553. __extends(PushMaterial, _super);
  28554. function PushMaterial(name, scene) {
  28555. var _this = _super.call(this, name, scene) || this;
  28556. _this.storeEffectOnSubMeshes = true;
  28557. return _this;
  28558. }
  28559. PushMaterial.prototype.getEffect = function () {
  28560. return this._activeEffect;
  28561. };
  28562. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  28563. if (!mesh) {
  28564. return false;
  28565. }
  28566. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  28567. return true;
  28568. }
  28569. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  28570. };
  28571. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  28572. this._activeEffect.setMatrix("world", world);
  28573. };
  28574. PushMaterial.prototype.bind = function (world, mesh) {
  28575. if (!mesh) {
  28576. return;
  28577. }
  28578. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  28579. };
  28580. PushMaterial.prototype._afterBind = function (mesh, effect) {
  28581. if (effect === void 0) { effect = null; }
  28582. _super.prototype._afterBind.call(this, mesh);
  28583. this.getScene()._cachedEffect = effect;
  28584. };
  28585. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  28586. if (visibility === void 0) { visibility = 1; }
  28587. return scene.isCachedMaterialInvalid(this, effect, visibility);
  28588. };
  28589. return PushMaterial;
  28590. }(BABYLON.Material));
  28591. BABYLON.PushMaterial = PushMaterial;
  28592. })(BABYLON || (BABYLON = {}));
  28593. //# sourceMappingURL=babylon.pushMaterial.js.map
  28594. var BABYLON;
  28595. (function (BABYLON) {
  28596. var VertexData = /** @class */ (function () {
  28597. function VertexData() {
  28598. }
  28599. VertexData.prototype.set = function (data, kind) {
  28600. switch (kind) {
  28601. case BABYLON.VertexBuffer.PositionKind:
  28602. this.positions = data;
  28603. break;
  28604. case BABYLON.VertexBuffer.NormalKind:
  28605. this.normals = data;
  28606. break;
  28607. case BABYLON.VertexBuffer.TangentKind:
  28608. this.tangents = data;
  28609. break;
  28610. case BABYLON.VertexBuffer.UVKind:
  28611. this.uvs = data;
  28612. break;
  28613. case BABYLON.VertexBuffer.UV2Kind:
  28614. this.uvs2 = data;
  28615. break;
  28616. case BABYLON.VertexBuffer.UV3Kind:
  28617. this.uvs3 = data;
  28618. break;
  28619. case BABYLON.VertexBuffer.UV4Kind:
  28620. this.uvs4 = data;
  28621. break;
  28622. case BABYLON.VertexBuffer.UV5Kind:
  28623. this.uvs5 = data;
  28624. break;
  28625. case BABYLON.VertexBuffer.UV6Kind:
  28626. this.uvs6 = data;
  28627. break;
  28628. case BABYLON.VertexBuffer.ColorKind:
  28629. this.colors = data;
  28630. break;
  28631. case BABYLON.VertexBuffer.MatricesIndicesKind:
  28632. this.matricesIndices = data;
  28633. break;
  28634. case BABYLON.VertexBuffer.MatricesWeightsKind:
  28635. this.matricesWeights = data;
  28636. break;
  28637. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  28638. this.matricesIndicesExtra = data;
  28639. break;
  28640. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  28641. this.matricesWeightsExtra = data;
  28642. break;
  28643. }
  28644. };
  28645. /**
  28646. * Associates the vertexData to the passed Mesh.
  28647. * Sets it as updatable or not (default `false`).
  28648. * Returns the VertexData.
  28649. */
  28650. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  28651. this._applyTo(mesh, updatable);
  28652. return this;
  28653. };
  28654. /**
  28655. * Associates the vertexData to the passed Geometry.
  28656. * Sets it as updatable or not (default `false`).
  28657. * Returns the VertexData.
  28658. */
  28659. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  28660. this._applyTo(geometry, updatable);
  28661. return this;
  28662. };
  28663. /**
  28664. * Updates the associated mesh.
  28665. * Returns the VertexData.
  28666. */
  28667. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  28668. this._update(mesh);
  28669. return this;
  28670. };
  28671. /**
  28672. * Updates the associated geometry.
  28673. * Returns the VertexData.
  28674. */
  28675. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  28676. this._update(geometry);
  28677. return this;
  28678. };
  28679. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  28680. if (updatable === void 0) { updatable = false; }
  28681. if (this.positions) {
  28682. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  28683. }
  28684. if (this.normals) {
  28685. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  28686. }
  28687. if (this.tangents) {
  28688. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  28689. }
  28690. if (this.uvs) {
  28691. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  28692. }
  28693. if (this.uvs2) {
  28694. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  28695. }
  28696. if (this.uvs3) {
  28697. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  28698. }
  28699. if (this.uvs4) {
  28700. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  28701. }
  28702. if (this.uvs5) {
  28703. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  28704. }
  28705. if (this.uvs6) {
  28706. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  28707. }
  28708. if (this.colors) {
  28709. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  28710. }
  28711. if (this.matricesIndices) {
  28712. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  28713. }
  28714. if (this.matricesWeights) {
  28715. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  28716. }
  28717. if (this.matricesIndicesExtra) {
  28718. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  28719. }
  28720. if (this.matricesWeightsExtra) {
  28721. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  28722. }
  28723. if (this.indices) {
  28724. meshOrGeometry.setIndices(this.indices, null, updatable);
  28725. }
  28726. return this;
  28727. };
  28728. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  28729. if (this.positions) {
  28730. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  28731. }
  28732. if (this.normals) {
  28733. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  28734. }
  28735. if (this.tangents) {
  28736. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  28737. }
  28738. if (this.uvs) {
  28739. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  28740. }
  28741. if (this.uvs2) {
  28742. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  28743. }
  28744. if (this.uvs3) {
  28745. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  28746. }
  28747. if (this.uvs4) {
  28748. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  28749. }
  28750. if (this.uvs5) {
  28751. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  28752. }
  28753. if (this.uvs6) {
  28754. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  28755. }
  28756. if (this.colors) {
  28757. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  28758. }
  28759. if (this.matricesIndices) {
  28760. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  28761. }
  28762. if (this.matricesWeights) {
  28763. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  28764. }
  28765. if (this.matricesIndicesExtra) {
  28766. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  28767. }
  28768. if (this.matricesWeightsExtra) {
  28769. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  28770. }
  28771. if (this.indices) {
  28772. meshOrGeometry.setIndices(this.indices, null);
  28773. }
  28774. return this;
  28775. };
  28776. /**
  28777. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  28778. * Returns the VertexData.
  28779. */
  28780. VertexData.prototype.transform = function (matrix) {
  28781. var transformed = BABYLON.Vector3.Zero();
  28782. var index;
  28783. if (this.positions) {
  28784. var position = BABYLON.Vector3.Zero();
  28785. for (index = 0; index < this.positions.length; index += 3) {
  28786. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  28787. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  28788. this.positions[index] = transformed.x;
  28789. this.positions[index + 1] = transformed.y;
  28790. this.positions[index + 2] = transformed.z;
  28791. }
  28792. }
  28793. if (this.normals) {
  28794. var normal = BABYLON.Vector3.Zero();
  28795. for (index = 0; index < this.normals.length; index += 3) {
  28796. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  28797. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  28798. this.normals[index] = transformed.x;
  28799. this.normals[index + 1] = transformed.y;
  28800. this.normals[index + 2] = transformed.z;
  28801. }
  28802. }
  28803. if (this.tangents) {
  28804. var tangent = BABYLON.Vector4.Zero();
  28805. var tangentTransformed = BABYLON.Vector4.Zero();
  28806. for (index = 0; index < this.tangents.length; index += 4) {
  28807. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  28808. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  28809. this.tangents[index] = tangentTransformed.x;
  28810. this.tangents[index + 1] = tangentTransformed.y;
  28811. this.tangents[index + 2] = tangentTransformed.z;
  28812. this.tangents[index + 3] = tangentTransformed.w;
  28813. }
  28814. }
  28815. return this;
  28816. };
  28817. /**
  28818. * Merges the passed VertexData into the current one.
  28819. * Returns the modified VertexData.
  28820. */
  28821. VertexData.prototype.merge = function (other, options) {
  28822. options = options || {};
  28823. if (other.indices) {
  28824. if (!this.indices) {
  28825. this.indices = [];
  28826. }
  28827. var offset = this.positions ? this.positions.length / 3 : 0;
  28828. for (var index = 0; index < other.indices.length; index++) {
  28829. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  28830. this.indices.push(other.indices[index] + offset);
  28831. }
  28832. }
  28833. this.positions = this._mergeElement(this.positions, other.positions);
  28834. if (!this.positions) {
  28835. return this;
  28836. }
  28837. var count = this.positions.length / 3;
  28838. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  28839. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  28840. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  28841. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  28842. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  28843. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  28844. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  28845. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  28846. this.colors = this._mergeElement(this.colors, other.colors, count * 4);
  28847. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  28848. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  28849. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  28850. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  28851. return this;
  28852. };
  28853. VertexData.prototype._mergeElement = function (source, other, length) {
  28854. if (length === void 0) { length = 0; }
  28855. if (!other && !source) {
  28856. return null;
  28857. }
  28858. if (!other) {
  28859. return this._mergeElement(source, new Float32Array(source.length), length);
  28860. }
  28861. if (!source) {
  28862. if (length === 0 || length === other.length) {
  28863. return other;
  28864. }
  28865. return this._mergeElement(new Float32Array(length - other.length), other, length);
  28866. }
  28867. var len = other.length + source.length;
  28868. var isSrcTypedArray = source instanceof Float32Array;
  28869. var isOthTypedArray = other instanceof Float32Array;
  28870. // use non-loop method when the source is Float32Array
  28871. if (isSrcTypedArray) {
  28872. var ret32 = new Float32Array(len);
  28873. ret32.set(source);
  28874. ret32.set(other, source.length);
  28875. return ret32;
  28876. // source is number[], when other is also use concat
  28877. }
  28878. else if (!isOthTypedArray) {
  28879. return source.concat(other);
  28880. // source is a number[], but other is a Float32Array, loop required
  28881. }
  28882. else {
  28883. var ret = source.slice(0); // copy source to a separate array
  28884. for (var i = 0, len = other.length; i < len; i++) {
  28885. ret.push(other[i]);
  28886. }
  28887. return ret;
  28888. }
  28889. };
  28890. /**
  28891. * Serializes the VertexData.
  28892. * Returns a serialized object.
  28893. */
  28894. VertexData.prototype.serialize = function () {
  28895. var serializationObject = this.serialize();
  28896. if (this.positions) {
  28897. serializationObject.positions = this.positions;
  28898. }
  28899. if (this.normals) {
  28900. serializationObject.normals = this.normals;
  28901. }
  28902. if (this.tangents) {
  28903. serializationObject.tangents = this.tangents;
  28904. }
  28905. if (this.uvs) {
  28906. serializationObject.uvs = this.uvs;
  28907. }
  28908. if (this.uvs2) {
  28909. serializationObject.uvs2 = this.uvs2;
  28910. }
  28911. if (this.uvs3) {
  28912. serializationObject.uvs3 = this.uvs3;
  28913. }
  28914. if (this.uvs4) {
  28915. serializationObject.uvs4 = this.uvs4;
  28916. }
  28917. if (this.uvs5) {
  28918. serializationObject.uvs5 = this.uvs5;
  28919. }
  28920. if (this.uvs6) {
  28921. serializationObject.uvs6 = this.uvs6;
  28922. }
  28923. if (this.colors) {
  28924. serializationObject.colors = this.colors;
  28925. }
  28926. if (this.matricesIndices) {
  28927. serializationObject.matricesIndices = this.matricesIndices;
  28928. serializationObject.matricesIndices._isExpanded = true;
  28929. }
  28930. if (this.matricesWeights) {
  28931. serializationObject.matricesWeights = this.matricesWeights;
  28932. }
  28933. if (this.matricesIndicesExtra) {
  28934. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  28935. serializationObject.matricesIndicesExtra._isExpanded = true;
  28936. }
  28937. if (this.matricesWeightsExtra) {
  28938. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  28939. }
  28940. serializationObject.indices = this.indices;
  28941. return serializationObject;
  28942. };
  28943. // Statics
  28944. /**
  28945. * Returns the object VertexData associated to the passed mesh.
  28946. */
  28947. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  28948. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  28949. };
  28950. /**
  28951. * Returns the object VertexData associated to the passed geometry.
  28952. */
  28953. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  28954. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  28955. };
  28956. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  28957. var result = new VertexData();
  28958. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28959. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  28960. }
  28961. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28962. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  28963. }
  28964. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  28965. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  28966. }
  28967. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28968. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  28969. }
  28970. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28971. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  28972. }
  28973. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28974. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  28975. }
  28976. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28977. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  28978. }
  28979. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28980. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  28981. }
  28982. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28983. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  28984. }
  28985. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28986. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  28987. }
  28988. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28989. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  28990. }
  28991. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28992. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  28993. }
  28994. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  28995. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  28996. }
  28997. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  28998. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  28999. }
  29000. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  29001. return result;
  29002. };
  29003. /**
  29004. * Creates the vertexData of the Ribbon.
  29005. */
  29006. VertexData.CreateRibbon = function (options) {
  29007. var pathArray = options.pathArray;
  29008. var closeArray = options.closeArray || false;
  29009. var closePath = options.closePath || false;
  29010. var invertUV = options.invertUV || false;
  29011. var defaultOffset = Math.floor(pathArray[0].length / 2);
  29012. var offset = options.offset || defaultOffset;
  29013. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  29014. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29015. var customUV = options.uvs;
  29016. var customColors = options.colors;
  29017. var positions = [];
  29018. var indices = [];
  29019. var normals = [];
  29020. var uvs = [];
  29021. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  29022. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  29023. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  29024. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  29025. var minlg; // minimal length among all paths from pathArray
  29026. var lg = []; // array of path lengths : nb of vertex per path
  29027. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  29028. var p; // path iterator
  29029. var i; // point iterator
  29030. var j; // point iterator
  29031. // if single path in pathArray
  29032. if (pathArray.length < 2) {
  29033. var ar1 = [];
  29034. var ar2 = [];
  29035. for (i = 0; i < pathArray[0].length - offset; i++) {
  29036. ar1.push(pathArray[0][i]);
  29037. ar2.push(pathArray[0][i + offset]);
  29038. }
  29039. pathArray = [ar1, ar2];
  29040. }
  29041. // positions and horizontal distances (u)
  29042. var idc = 0;
  29043. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  29044. var path;
  29045. var l;
  29046. minlg = pathArray[0].length;
  29047. var vectlg;
  29048. var dist;
  29049. for (p = 0; p < pathArray.length; p++) {
  29050. uTotalDistance[p] = 0;
  29051. us[p] = [0];
  29052. path = pathArray[p];
  29053. l = path.length;
  29054. minlg = (minlg < l) ? minlg : l;
  29055. j = 0;
  29056. while (j < l) {
  29057. positions.push(path[j].x, path[j].y, path[j].z);
  29058. if (j > 0) {
  29059. vectlg = path[j].subtract(path[j - 1]).length();
  29060. dist = vectlg + uTotalDistance[p];
  29061. us[p].push(dist);
  29062. uTotalDistance[p] = dist;
  29063. }
  29064. j++;
  29065. }
  29066. if (closePath) {
  29067. j--;
  29068. positions.push(path[0].x, path[0].y, path[0].z);
  29069. vectlg = path[j].subtract(path[0]).length();
  29070. dist = vectlg + uTotalDistance[p];
  29071. us[p].push(dist);
  29072. uTotalDistance[p] = dist;
  29073. }
  29074. lg[p] = l + closePathCorr;
  29075. idx[p] = idc;
  29076. idc += (l + closePathCorr);
  29077. }
  29078. // vertical distances (v)
  29079. var path1;
  29080. var path2;
  29081. var vertex1 = null;
  29082. var vertex2 = null;
  29083. for (i = 0; i < minlg + closePathCorr; i++) {
  29084. vTotalDistance[i] = 0;
  29085. vs[i] = [0];
  29086. for (p = 0; p < pathArray.length - 1; p++) {
  29087. path1 = pathArray[p];
  29088. path2 = pathArray[p + 1];
  29089. if (i === minlg) {
  29090. vertex1 = path1[0];
  29091. vertex2 = path2[0];
  29092. }
  29093. else {
  29094. vertex1 = path1[i];
  29095. vertex2 = path2[i];
  29096. }
  29097. vectlg = vertex2.subtract(vertex1).length();
  29098. dist = vectlg + vTotalDistance[i];
  29099. vs[i].push(dist);
  29100. vTotalDistance[i] = dist;
  29101. }
  29102. if (closeArray && vertex2 && vertex1) {
  29103. path1 = pathArray[p];
  29104. path2 = pathArray[0];
  29105. if (i === minlg) {
  29106. vertex2 = path2[0];
  29107. }
  29108. vectlg = vertex2.subtract(vertex1).length();
  29109. dist = vectlg + vTotalDistance[i];
  29110. vTotalDistance[i] = dist;
  29111. }
  29112. }
  29113. // uvs
  29114. var u;
  29115. var v;
  29116. if (customUV) {
  29117. for (p = 0; p < customUV.length; p++) {
  29118. uvs.push(customUV[p].x, customUV[p].y);
  29119. }
  29120. }
  29121. else {
  29122. for (p = 0; p < pathArray.length; p++) {
  29123. for (i = 0; i < minlg + closePathCorr; i++) {
  29124. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  29125. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  29126. if (invertUV) {
  29127. uvs.push(v, u);
  29128. }
  29129. else {
  29130. uvs.push(u, v);
  29131. }
  29132. }
  29133. }
  29134. }
  29135. // indices
  29136. p = 0; // path index
  29137. var pi = 0; // positions array index
  29138. var l1 = lg[p] - 1; // path1 length
  29139. var l2 = lg[p + 1] - 1; // path2 length
  29140. var min = (l1 < l2) ? l1 : l2; // current path stop index
  29141. var shft = idx[1] - idx[0]; // shift
  29142. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  29143. while (pi <= min && p < path1nb) {
  29144. // 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
  29145. indices.push(pi, pi + shft, pi + 1);
  29146. indices.push(pi + shft + 1, pi + 1, pi + shft);
  29147. pi += 1;
  29148. if (pi === min) {
  29149. p++;
  29150. if (p === lg.length - 1) {
  29151. shft = idx[0] - idx[p];
  29152. l1 = lg[p] - 1;
  29153. l2 = lg[0] - 1;
  29154. }
  29155. else {
  29156. shft = idx[p + 1] - idx[p];
  29157. l1 = lg[p] - 1;
  29158. l2 = lg[p + 1] - 1;
  29159. }
  29160. pi = idx[p];
  29161. min = (l1 < l2) ? l1 + pi : l2 + pi;
  29162. }
  29163. }
  29164. // normals
  29165. VertexData.ComputeNormals(positions, indices, normals);
  29166. if (closePath) {
  29167. var indexFirst = 0;
  29168. var indexLast = 0;
  29169. for (p = 0; p < pathArray.length; p++) {
  29170. indexFirst = idx[p] * 3;
  29171. if (p + 1 < pathArray.length) {
  29172. indexLast = (idx[p + 1] - 1) * 3;
  29173. }
  29174. else {
  29175. indexLast = normals.length - 3;
  29176. }
  29177. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  29178. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  29179. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  29180. normals[indexLast] = normals[indexFirst];
  29181. normals[indexLast + 1] = normals[indexFirst + 1];
  29182. normals[indexLast + 2] = normals[indexFirst + 2];
  29183. }
  29184. }
  29185. // sides
  29186. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29187. // Colors
  29188. var colors = null;
  29189. if (customColors) {
  29190. colors = new Float32Array(customColors.length * 4);
  29191. for (var c = 0; c < customColors.length; c++) {
  29192. colors[c * 4] = customColors[c].r;
  29193. colors[c * 4 + 1] = customColors[c].g;
  29194. colors[c * 4 + 2] = customColors[c].b;
  29195. colors[c * 4 + 3] = customColors[c].a;
  29196. }
  29197. }
  29198. // Result
  29199. var vertexData = new VertexData();
  29200. var positions32 = new Float32Array(positions);
  29201. var normals32 = new Float32Array(normals);
  29202. var uvs32 = new Float32Array(uvs);
  29203. vertexData.indices = indices;
  29204. vertexData.positions = positions32;
  29205. vertexData.normals = normals32;
  29206. vertexData.uvs = uvs32;
  29207. if (colors) {
  29208. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  29209. }
  29210. if (closePath) {
  29211. vertexData._idx = idx;
  29212. }
  29213. return vertexData;
  29214. };
  29215. /**
  29216. * Creates the VertexData of the Box.
  29217. */
  29218. VertexData.CreateBox = function (options) {
  29219. var normalsSource = [
  29220. new BABYLON.Vector3(0, 0, 1),
  29221. new BABYLON.Vector3(0, 0, -1),
  29222. new BABYLON.Vector3(1, 0, 0),
  29223. new BABYLON.Vector3(-1, 0, 0),
  29224. new BABYLON.Vector3(0, 1, 0),
  29225. new BABYLON.Vector3(0, -1, 0)
  29226. ];
  29227. var indices = [];
  29228. var positions = [];
  29229. var normals = [];
  29230. var uvs = [];
  29231. var width = options.width || options.size || 1;
  29232. var height = options.height || options.size || 1;
  29233. var depth = options.depth || options.size || 1;
  29234. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29235. var faceUV = options.faceUV || new Array(6);
  29236. var faceColors = options.faceColors;
  29237. var colors = [];
  29238. // default face colors and UV if undefined
  29239. for (var f = 0; f < 6; f++) {
  29240. if (faceUV[f] === undefined) {
  29241. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29242. }
  29243. if (faceColors && faceColors[f] === undefined) {
  29244. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29245. }
  29246. }
  29247. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  29248. // Create each face in turn.
  29249. for (var index = 0; index < normalsSource.length; index++) {
  29250. var normal = normalsSource[index];
  29251. // Get two vectors perpendicular to the face normal and to each other.
  29252. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  29253. var side2 = BABYLON.Vector3.Cross(normal, side1);
  29254. // Six indices (two triangles) per face.
  29255. var verticesLength = positions.length / 3;
  29256. indices.push(verticesLength);
  29257. indices.push(verticesLength + 1);
  29258. indices.push(verticesLength + 2);
  29259. indices.push(verticesLength);
  29260. indices.push(verticesLength + 2);
  29261. indices.push(verticesLength + 3);
  29262. // Four vertices per face.
  29263. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  29264. positions.push(vertex.x, vertex.y, vertex.z);
  29265. normals.push(normal.x, normal.y, normal.z);
  29266. uvs.push(faceUV[index].z, faceUV[index].w);
  29267. if (faceColors) {
  29268. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29269. }
  29270. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  29271. positions.push(vertex.x, vertex.y, vertex.z);
  29272. normals.push(normal.x, normal.y, normal.z);
  29273. uvs.push(faceUV[index].x, faceUV[index].w);
  29274. if (faceColors) {
  29275. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29276. }
  29277. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  29278. positions.push(vertex.x, vertex.y, vertex.z);
  29279. normals.push(normal.x, normal.y, normal.z);
  29280. uvs.push(faceUV[index].x, faceUV[index].y);
  29281. if (faceColors) {
  29282. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29283. }
  29284. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  29285. positions.push(vertex.x, vertex.y, vertex.z);
  29286. normals.push(normal.x, normal.y, normal.z);
  29287. uvs.push(faceUV[index].z, faceUV[index].y);
  29288. if (faceColors) {
  29289. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29290. }
  29291. }
  29292. // sides
  29293. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29294. // Result
  29295. var vertexData = new VertexData();
  29296. vertexData.indices = indices;
  29297. vertexData.positions = positions;
  29298. vertexData.normals = normals;
  29299. vertexData.uvs = uvs;
  29300. if (faceColors) {
  29301. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29302. vertexData.colors = totalColors;
  29303. }
  29304. return vertexData;
  29305. };
  29306. /**
  29307. * Creates the VertexData of the Sphere.
  29308. */
  29309. VertexData.CreateSphere = function (options) {
  29310. var segments = options.segments || 32;
  29311. var diameterX = options.diameterX || options.diameter || 1;
  29312. var diameterY = options.diameterY || options.diameter || 1;
  29313. var diameterZ = options.diameterZ || options.diameter || 1;
  29314. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29315. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  29316. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29317. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  29318. var totalZRotationSteps = 2 + segments;
  29319. var totalYRotationSteps = 2 * totalZRotationSteps;
  29320. var indices = [];
  29321. var positions = [];
  29322. var normals = [];
  29323. var uvs = [];
  29324. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  29325. var normalizedZ = zRotationStep / totalZRotationSteps;
  29326. var angleZ = normalizedZ * Math.PI * slice;
  29327. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  29328. var normalizedY = yRotationStep / totalYRotationSteps;
  29329. var angleY = normalizedY * Math.PI * 2 * arc;
  29330. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  29331. var rotationY = BABYLON.Matrix.RotationY(angleY);
  29332. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  29333. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  29334. var vertex = complete.multiply(radius);
  29335. var normal = complete.divide(radius).normalize();
  29336. positions.push(vertex.x, vertex.y, vertex.z);
  29337. normals.push(normal.x, normal.y, normal.z);
  29338. uvs.push(normalizedY, normalizedZ);
  29339. }
  29340. if (zRotationStep > 0) {
  29341. var verticesCount = positions.length / 3;
  29342. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  29343. indices.push((firstIndex));
  29344. indices.push((firstIndex + 1));
  29345. indices.push(firstIndex + totalYRotationSteps + 1);
  29346. indices.push((firstIndex + totalYRotationSteps + 1));
  29347. indices.push((firstIndex + 1));
  29348. indices.push((firstIndex + totalYRotationSteps + 2));
  29349. }
  29350. }
  29351. }
  29352. // Sides
  29353. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29354. // Result
  29355. var vertexData = new VertexData();
  29356. vertexData.indices = indices;
  29357. vertexData.positions = positions;
  29358. vertexData.normals = normals;
  29359. vertexData.uvs = uvs;
  29360. return vertexData;
  29361. };
  29362. /**
  29363. * Creates the VertexData of the Cylinder or Cone.
  29364. */
  29365. VertexData.CreateCylinder = function (options) {
  29366. var height = options.height || 2;
  29367. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  29368. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  29369. var tessellation = options.tessellation || 24;
  29370. var subdivisions = options.subdivisions || 1;
  29371. var hasRings = options.hasRings ? true : false;
  29372. var enclose = options.enclose ? true : false;
  29373. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29374. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29375. var faceUV = options.faceUV || new Array(3);
  29376. var faceColors = options.faceColors;
  29377. // default face colors and UV if undefined
  29378. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  29379. var ringNb = (hasRings) ? subdivisions : 1;
  29380. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  29381. var f;
  29382. for (f = 0; f < surfaceNb; f++) {
  29383. if (faceColors && faceColors[f] === undefined) {
  29384. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29385. }
  29386. }
  29387. for (f = 0; f < surfaceNb; f++) {
  29388. if (faceUV && faceUV[f] === undefined) {
  29389. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29390. }
  29391. }
  29392. var indices = new Array();
  29393. var positions = new Array();
  29394. var normals = new Array();
  29395. var uvs = new Array();
  29396. var colors = new Array();
  29397. var angle_step = Math.PI * 2 * arc / tessellation;
  29398. var angle;
  29399. var h;
  29400. var radius;
  29401. var tan = (diameterBottom - diameterTop) / 2 / height;
  29402. var ringVertex = BABYLON.Vector3.Zero();
  29403. var ringNormal = BABYLON.Vector3.Zero();
  29404. var ringFirstVertex = BABYLON.Vector3.Zero();
  29405. var ringFirstNormal = BABYLON.Vector3.Zero();
  29406. var quadNormal = BABYLON.Vector3.Zero();
  29407. var Y = BABYLON.Axis.Y;
  29408. // positions, normals, uvs
  29409. var i;
  29410. var j;
  29411. var r;
  29412. var ringIdx = 1;
  29413. var s = 1; // surface index
  29414. var cs = 0;
  29415. var v = 0;
  29416. for (i = 0; i <= subdivisions; i++) {
  29417. h = i / subdivisions;
  29418. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  29419. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  29420. for (r = 0; r < ringIdx; r++) {
  29421. if (hasRings) {
  29422. s += r;
  29423. }
  29424. if (enclose) {
  29425. s += 2 * r;
  29426. }
  29427. for (j = 0; j <= tessellation; j++) {
  29428. angle = j * angle_step;
  29429. // position
  29430. ringVertex.x = Math.cos(-angle) * radius;
  29431. ringVertex.y = -height / 2 + h * height;
  29432. ringVertex.z = Math.sin(-angle) * radius;
  29433. // normal
  29434. if (diameterTop === 0 && i === subdivisions) {
  29435. // if no top cap, reuse former normals
  29436. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  29437. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  29438. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  29439. }
  29440. else {
  29441. ringNormal.x = ringVertex.x;
  29442. ringNormal.z = ringVertex.z;
  29443. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  29444. ringNormal.normalize();
  29445. }
  29446. // keep first ring vertex values for enclose
  29447. if (j === 0) {
  29448. ringFirstVertex.copyFrom(ringVertex);
  29449. ringFirstNormal.copyFrom(ringNormal);
  29450. }
  29451. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29452. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  29453. if (hasRings) {
  29454. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  29455. }
  29456. else {
  29457. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  29458. }
  29459. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  29460. if (faceColors) {
  29461. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  29462. }
  29463. }
  29464. // if enclose, add four vertices and their dedicated normals
  29465. if (arc !== 1 && enclose) {
  29466. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29467. positions.push(0, ringVertex.y, 0);
  29468. positions.push(0, ringVertex.y, 0);
  29469. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  29470. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  29471. quadNormal.normalize();
  29472. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29473. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  29474. quadNormal.normalize();
  29475. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29476. if (hasRings) {
  29477. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  29478. }
  29479. else {
  29480. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  29481. }
  29482. uvs.push(faceUV[s + 1].x, v);
  29483. uvs.push(faceUV[s + 1].z, v);
  29484. if (hasRings) {
  29485. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  29486. }
  29487. else {
  29488. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  29489. }
  29490. uvs.push(faceUV[s + 2].x, v);
  29491. uvs.push(faceUV[s + 2].z, v);
  29492. if (faceColors) {
  29493. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29494. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29495. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29496. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29497. }
  29498. }
  29499. if (cs !== s) {
  29500. cs = s;
  29501. }
  29502. }
  29503. }
  29504. // indices
  29505. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  29506. var s;
  29507. i = 0;
  29508. for (s = 0; s < subdivisions; s++) {
  29509. var i0 = 0;
  29510. var i1 = 0;
  29511. var i2 = 0;
  29512. var i3 = 0;
  29513. for (j = 0; j < tessellation; j++) {
  29514. i0 = i * (e + 1) + j;
  29515. i1 = (i + 1) * (e + 1) + j;
  29516. i2 = i * (e + 1) + (j + 1);
  29517. i3 = (i + 1) * (e + 1) + (j + 1);
  29518. indices.push(i0, i1, i2);
  29519. indices.push(i3, i2, i1);
  29520. }
  29521. if (arc !== 1 && enclose) {
  29522. indices.push(i0 + 2, i1 + 2, i2 + 2);
  29523. indices.push(i3 + 2, i2 + 2, i1 + 2);
  29524. indices.push(i0 + 4, i1 + 4, i2 + 4);
  29525. indices.push(i3 + 4, i2 + 4, i1 + 4);
  29526. }
  29527. i = (hasRings) ? (i + 2) : (i + 1);
  29528. }
  29529. // Caps
  29530. var createCylinderCap = function (isTop) {
  29531. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  29532. if (radius === 0) {
  29533. return;
  29534. }
  29535. // Cap positions, normals & uvs
  29536. var angle;
  29537. var circleVector;
  29538. var i;
  29539. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  29540. var c = null;
  29541. if (faceColors) {
  29542. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  29543. }
  29544. // cap center
  29545. var vbase = positions.length / 3;
  29546. var offset = isTop ? height / 2 : -height / 2;
  29547. var center = new BABYLON.Vector3(0, offset, 0);
  29548. positions.push(center.x, center.y, center.z);
  29549. normals.push(0, isTop ? 1 : -1, 0);
  29550. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  29551. if (c) {
  29552. colors.push(c.r, c.g, c.b, c.a);
  29553. }
  29554. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  29555. for (i = 0; i <= tessellation; i++) {
  29556. angle = Math.PI * 2 * i * arc / tessellation;
  29557. var cos = Math.cos(-angle);
  29558. var sin = Math.sin(-angle);
  29559. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  29560. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  29561. positions.push(circleVector.x, circleVector.y, circleVector.z);
  29562. normals.push(0, isTop ? 1 : -1, 0);
  29563. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  29564. if (c) {
  29565. colors.push(c.r, c.g, c.b, c.a);
  29566. }
  29567. }
  29568. // Cap indices
  29569. for (i = 0; i < tessellation; i++) {
  29570. if (!isTop) {
  29571. indices.push(vbase);
  29572. indices.push(vbase + (i + 1));
  29573. indices.push(vbase + (i + 2));
  29574. }
  29575. else {
  29576. indices.push(vbase);
  29577. indices.push(vbase + (i + 2));
  29578. indices.push(vbase + (i + 1));
  29579. }
  29580. }
  29581. };
  29582. // add caps to geometry
  29583. createCylinderCap(false);
  29584. createCylinderCap(true);
  29585. // Sides
  29586. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29587. var vertexData = new VertexData();
  29588. vertexData.indices = indices;
  29589. vertexData.positions = positions;
  29590. vertexData.normals = normals;
  29591. vertexData.uvs = uvs;
  29592. if (faceColors) {
  29593. vertexData.colors = colors;
  29594. }
  29595. return vertexData;
  29596. };
  29597. /**
  29598. * Creates the VertexData of the Torus.
  29599. */
  29600. VertexData.CreateTorus = function (options) {
  29601. var indices = [];
  29602. var positions = [];
  29603. var normals = [];
  29604. var uvs = [];
  29605. var diameter = options.diameter || 1;
  29606. var thickness = options.thickness || 0.5;
  29607. var tessellation = options.tessellation || 16;
  29608. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29609. var stride = tessellation + 1;
  29610. for (var i = 0; i <= tessellation; i++) {
  29611. var u = i / tessellation;
  29612. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  29613. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  29614. for (var j = 0; j <= tessellation; j++) {
  29615. var v = 1 - j / tessellation;
  29616. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  29617. var dx = Math.cos(innerAngle);
  29618. var dy = Math.sin(innerAngle);
  29619. // Create a vertex.
  29620. var normal = new BABYLON.Vector3(dx, dy, 0);
  29621. var position = normal.scale(thickness / 2);
  29622. var textureCoordinate = new BABYLON.Vector2(u, v);
  29623. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  29624. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  29625. positions.push(position.x, position.y, position.z);
  29626. normals.push(normal.x, normal.y, normal.z);
  29627. uvs.push(textureCoordinate.x, textureCoordinate.y);
  29628. // And create indices for two triangles.
  29629. var nextI = (i + 1) % stride;
  29630. var nextJ = (j + 1) % stride;
  29631. indices.push(i * stride + j);
  29632. indices.push(i * stride + nextJ);
  29633. indices.push(nextI * stride + j);
  29634. indices.push(i * stride + nextJ);
  29635. indices.push(nextI * stride + nextJ);
  29636. indices.push(nextI * stride + j);
  29637. }
  29638. }
  29639. // Sides
  29640. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29641. // Result
  29642. var vertexData = new VertexData();
  29643. vertexData.indices = indices;
  29644. vertexData.positions = positions;
  29645. vertexData.normals = normals;
  29646. vertexData.uvs = uvs;
  29647. return vertexData;
  29648. };
  29649. /**
  29650. * Creates the VertexData of the LineSystem.
  29651. */
  29652. VertexData.CreateLineSystem = function (options) {
  29653. var indices = [];
  29654. var positions = [];
  29655. var lines = options.lines;
  29656. var colors = options.colors;
  29657. var vertexColors = [];
  29658. var idx = 0;
  29659. for (var l = 0; l < lines.length; l++) {
  29660. var points = lines[l];
  29661. for (var index = 0; index < points.length; index++) {
  29662. positions.push(points[index].x, points[index].y, points[index].z);
  29663. if (colors) {
  29664. var color = colors[l];
  29665. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  29666. }
  29667. if (index > 0) {
  29668. indices.push(idx - 1);
  29669. indices.push(idx);
  29670. }
  29671. idx++;
  29672. }
  29673. }
  29674. var vertexData = new VertexData();
  29675. vertexData.indices = indices;
  29676. vertexData.positions = positions;
  29677. if (colors) {
  29678. vertexData.colors = vertexColors;
  29679. }
  29680. return vertexData;
  29681. };
  29682. /**
  29683. * Create the VertexData of the DashedLines.
  29684. */
  29685. VertexData.CreateDashedLines = function (options) {
  29686. var dashSize = options.dashSize || 3;
  29687. var gapSize = options.gapSize || 1;
  29688. var dashNb = options.dashNb || 200;
  29689. var points = options.points;
  29690. var positions = new Array();
  29691. var indices = new Array();
  29692. var curvect = BABYLON.Vector3.Zero();
  29693. var lg = 0;
  29694. var nb = 0;
  29695. var shft = 0;
  29696. var dashshft = 0;
  29697. var curshft = 0;
  29698. var idx = 0;
  29699. var i = 0;
  29700. for (i = 0; i < points.length - 1; i++) {
  29701. points[i + 1].subtractToRef(points[i], curvect);
  29702. lg += curvect.length();
  29703. }
  29704. shft = lg / dashNb;
  29705. dashshft = dashSize * shft / (dashSize + gapSize);
  29706. for (i = 0; i < points.length - 1; i++) {
  29707. points[i + 1].subtractToRef(points[i], curvect);
  29708. nb = Math.floor(curvect.length() / shft);
  29709. curvect.normalize();
  29710. for (var j = 0; j < nb; j++) {
  29711. curshft = shft * j;
  29712. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  29713. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  29714. indices.push(idx, idx + 1);
  29715. idx += 2;
  29716. }
  29717. }
  29718. // Result
  29719. var vertexData = new VertexData();
  29720. vertexData.positions = positions;
  29721. vertexData.indices = indices;
  29722. return vertexData;
  29723. };
  29724. /**
  29725. * Creates the VertexData of the Ground.
  29726. */
  29727. VertexData.CreateGround = function (options) {
  29728. var indices = [];
  29729. var positions = [];
  29730. var normals = [];
  29731. var uvs = [];
  29732. var row, col;
  29733. var width = options.width || 1;
  29734. var height = options.height || 1;
  29735. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  29736. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  29737. for (row = 0; row <= subdivisionsY; row++) {
  29738. for (col = 0; col <= subdivisionsX; col++) {
  29739. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  29740. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29741. positions.push(position.x, position.y, position.z);
  29742. normals.push(normal.x, normal.y, normal.z);
  29743. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  29744. }
  29745. }
  29746. for (row = 0; row < subdivisionsY; row++) {
  29747. for (col = 0; col < subdivisionsX; col++) {
  29748. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29749. indices.push(col + 1 + row * (subdivisionsX + 1));
  29750. indices.push(col + row * (subdivisionsX + 1));
  29751. indices.push(col + (row + 1) * (subdivisionsX + 1));
  29752. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29753. indices.push(col + row * (subdivisionsX + 1));
  29754. }
  29755. }
  29756. // Result
  29757. var vertexData = new VertexData();
  29758. vertexData.indices = indices;
  29759. vertexData.positions = positions;
  29760. vertexData.normals = normals;
  29761. vertexData.uvs = uvs;
  29762. return vertexData;
  29763. };
  29764. /**
  29765. * Creates the VertexData of the TiledGround.
  29766. */
  29767. VertexData.CreateTiledGround = function (options) {
  29768. var xmin = options.xmin || -1.0;
  29769. var zmin = options.zmin || -1.0;
  29770. var xmax = options.xmax || 1.0;
  29771. var zmax = options.zmax || 1.0;
  29772. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  29773. var precision = options.precision || { w: 1, h: 1 };
  29774. var indices = new Array();
  29775. var positions = new Array();
  29776. var normals = new Array();
  29777. var uvs = new Array();
  29778. var row, col, tileRow, tileCol;
  29779. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  29780. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  29781. precision.w = (precision.w < 1) ? 1 : precision.w;
  29782. precision.h = (precision.h < 1) ? 1 : precision.h;
  29783. var tileSize = {
  29784. 'w': (xmax - xmin) / subdivisions.w,
  29785. 'h': (zmax - zmin) / subdivisions.h
  29786. };
  29787. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  29788. // Indices
  29789. var base = positions.length / 3;
  29790. var rowLength = precision.w + 1;
  29791. for (row = 0; row < precision.h; row++) {
  29792. for (col = 0; col < precision.w; col++) {
  29793. var square = [
  29794. base + col + row * rowLength,
  29795. base + (col + 1) + row * rowLength,
  29796. base + (col + 1) + (row + 1) * rowLength,
  29797. base + col + (row + 1) * rowLength
  29798. ];
  29799. indices.push(square[1]);
  29800. indices.push(square[2]);
  29801. indices.push(square[3]);
  29802. indices.push(square[0]);
  29803. indices.push(square[1]);
  29804. indices.push(square[3]);
  29805. }
  29806. }
  29807. // Position, normals and uvs
  29808. var position = BABYLON.Vector3.Zero();
  29809. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29810. for (row = 0; row <= precision.h; row++) {
  29811. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  29812. for (col = 0; col <= precision.w; col++) {
  29813. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  29814. position.y = 0;
  29815. positions.push(position.x, position.y, position.z);
  29816. normals.push(normal.x, normal.y, normal.z);
  29817. uvs.push(col / precision.w, row / precision.h);
  29818. }
  29819. }
  29820. }
  29821. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  29822. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  29823. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  29824. }
  29825. }
  29826. // Result
  29827. var vertexData = new VertexData();
  29828. vertexData.indices = indices;
  29829. vertexData.positions = positions;
  29830. vertexData.normals = normals;
  29831. vertexData.uvs = uvs;
  29832. return vertexData;
  29833. };
  29834. /**
  29835. * Creates the VertexData of the Ground designed from a heightmap.
  29836. */
  29837. VertexData.CreateGroundFromHeightMap = function (options) {
  29838. var indices = [];
  29839. var positions = [];
  29840. var normals = [];
  29841. var uvs = [];
  29842. var row, col;
  29843. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  29844. // Vertices
  29845. for (row = 0; row <= options.subdivisions; row++) {
  29846. for (col = 0; col <= options.subdivisions; col++) {
  29847. 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));
  29848. // Compute height
  29849. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  29850. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  29851. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  29852. var r = options.buffer[pos] / 255.0;
  29853. var g = options.buffer[pos + 1] / 255.0;
  29854. var b = options.buffer[pos + 2] / 255.0;
  29855. var gradient = r * filter.r + g * filter.g + b * filter.b;
  29856. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  29857. // Add vertex
  29858. positions.push(position.x, position.y, position.z);
  29859. normals.push(0, 0, 0);
  29860. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  29861. }
  29862. }
  29863. // Indices
  29864. for (row = 0; row < options.subdivisions; row++) {
  29865. for (col = 0; col < options.subdivisions; col++) {
  29866. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29867. indices.push(col + 1 + row * (options.subdivisions + 1));
  29868. indices.push(col + row * (options.subdivisions + 1));
  29869. indices.push(col + (row + 1) * (options.subdivisions + 1));
  29870. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29871. indices.push(col + row * (options.subdivisions + 1));
  29872. }
  29873. }
  29874. // Normals
  29875. VertexData.ComputeNormals(positions, indices, normals);
  29876. // Result
  29877. var vertexData = new VertexData();
  29878. vertexData.indices = indices;
  29879. vertexData.positions = positions;
  29880. vertexData.normals = normals;
  29881. vertexData.uvs = uvs;
  29882. return vertexData;
  29883. };
  29884. /**
  29885. * Creates the VertexData of the Plane.
  29886. */
  29887. VertexData.CreatePlane = function (options) {
  29888. var indices = [];
  29889. var positions = [];
  29890. var normals = [];
  29891. var uvs = [];
  29892. var width = options.width || options.size || 1;
  29893. var height = options.height || options.size || 1;
  29894. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29895. // Vertices
  29896. var halfWidth = width / 2.0;
  29897. var halfHeight = height / 2.0;
  29898. positions.push(-halfWidth, -halfHeight, 0);
  29899. normals.push(0, 0, -1.0);
  29900. uvs.push(0.0, 0.0);
  29901. positions.push(halfWidth, -halfHeight, 0);
  29902. normals.push(0, 0, -1.0);
  29903. uvs.push(1.0, 0.0);
  29904. positions.push(halfWidth, halfHeight, 0);
  29905. normals.push(0, 0, -1.0);
  29906. uvs.push(1.0, 1.0);
  29907. positions.push(-halfWidth, halfHeight, 0);
  29908. normals.push(0, 0, -1.0);
  29909. uvs.push(0.0, 1.0);
  29910. // Indices
  29911. indices.push(0);
  29912. indices.push(1);
  29913. indices.push(2);
  29914. indices.push(0);
  29915. indices.push(2);
  29916. indices.push(3);
  29917. // Sides
  29918. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29919. // Result
  29920. var vertexData = new VertexData();
  29921. vertexData.indices = indices;
  29922. vertexData.positions = positions;
  29923. vertexData.normals = normals;
  29924. vertexData.uvs = uvs;
  29925. return vertexData;
  29926. };
  29927. /**
  29928. * Creates the VertexData of the Disc or regular Polygon.
  29929. */
  29930. VertexData.CreateDisc = function (options) {
  29931. var positions = new Array();
  29932. var indices = new Array();
  29933. var normals = new Array();
  29934. var uvs = new Array();
  29935. var radius = options.radius || 0.5;
  29936. var tessellation = options.tessellation || 64;
  29937. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29938. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29939. // positions and uvs
  29940. positions.push(0, 0, 0); // disc center first
  29941. uvs.push(0.5, 0.5);
  29942. var theta = Math.PI * 2 * arc;
  29943. var step = theta / tessellation;
  29944. for (var a = 0; a < theta; a += step) {
  29945. var x = Math.cos(a);
  29946. var y = Math.sin(a);
  29947. var u = (x + 1) / 2;
  29948. var v = (1 - y) / 2;
  29949. positions.push(radius * x, radius * y, 0);
  29950. uvs.push(u, v);
  29951. }
  29952. if (arc === 1) {
  29953. positions.push(positions[3], positions[4], positions[5]); // close the circle
  29954. uvs.push(uvs[2], uvs[3]);
  29955. }
  29956. //indices
  29957. var vertexNb = positions.length / 3;
  29958. for (var i = 1; i < vertexNb - 1; i++) {
  29959. indices.push(i + 1, 0, i);
  29960. }
  29961. // result
  29962. VertexData.ComputeNormals(positions, indices, normals);
  29963. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29964. var vertexData = new VertexData();
  29965. vertexData.indices = indices;
  29966. vertexData.positions = positions;
  29967. vertexData.normals = normals;
  29968. vertexData.uvs = uvs;
  29969. return vertexData;
  29970. };
  29971. /**
  29972. * Re-creates the VertexData of the Polygon for sideOrientation.
  29973. */
  29974. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  29975. var faceUV = fUV || new Array(3);
  29976. var faceColors = fColors;
  29977. var colors = [];
  29978. // default face colors and UV if undefined
  29979. for (var f = 0; f < 3; f++) {
  29980. if (faceUV[f] === undefined) {
  29981. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29982. }
  29983. if (faceColors && faceColors[f] === undefined) {
  29984. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29985. }
  29986. }
  29987. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29988. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29989. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29990. var indices = polygon.getIndices();
  29991. // set face colours and textures
  29992. var idx = 0;
  29993. var face = 0;
  29994. for (var index = 0; index < normals.length; index += 3) {
  29995. //Edge Face no. 1
  29996. if (Math.abs(normals[index + 1]) < 0.001) {
  29997. face = 1;
  29998. }
  29999. //Top Face no. 0
  30000. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  30001. face = 0;
  30002. }
  30003. //Bottom Face no. 2
  30004. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  30005. face = 2;
  30006. }
  30007. idx = index / 3;
  30008. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  30009. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  30010. if (faceColors) {
  30011. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  30012. }
  30013. }
  30014. // sides
  30015. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  30016. // Result
  30017. var vertexData = new VertexData();
  30018. vertexData.indices = indices;
  30019. vertexData.positions = positions;
  30020. vertexData.normals = normals;
  30021. vertexData.uvs = uvs;
  30022. if (faceColors) {
  30023. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30024. vertexData.colors = totalColors;
  30025. }
  30026. return vertexData;
  30027. };
  30028. /**
  30029. * Creates the VertexData of the IcoSphere.
  30030. */
  30031. VertexData.CreateIcoSphere = function (options) {
  30032. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30033. var radius = options.radius || 1;
  30034. var flat = (options.flat === undefined) ? true : options.flat;
  30035. var subdivisions = options.subdivisions || 4;
  30036. var radiusX = options.radiusX || radius;
  30037. var radiusY = options.radiusY || radius;
  30038. var radiusZ = options.radiusZ || radius;
  30039. var t = (1 + Math.sqrt(5)) / 2;
  30040. // 12 vertex x,y,z
  30041. var ico_vertices = [
  30042. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  30043. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  30044. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  30045. ];
  30046. // index of 3 vertex makes a face of icopshere
  30047. var ico_indices = [
  30048. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  30049. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  30050. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  30051. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  30052. ];
  30053. // vertex for uv have aliased position, not for UV
  30054. var vertices_unalias_id = [
  30055. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  30056. // vertex alias
  30057. 0,
  30058. 2,
  30059. 3,
  30060. 3,
  30061. 3,
  30062. 4,
  30063. 7,
  30064. 8,
  30065. 9,
  30066. 9,
  30067. 10,
  30068. 11 // 23: B + 12
  30069. ];
  30070. // uv as integer step (not pixels !)
  30071. var ico_vertexuv = [
  30072. 5, 1, 3, 1, 6, 4, 0, 0,
  30073. 5, 3, 4, 2, 2, 2, 4, 0,
  30074. 2, 0, 1, 1, 6, 0, 6, 2,
  30075. // vertex alias (for same vertex on different faces)
  30076. 0, 4,
  30077. 3, 3,
  30078. 4, 4,
  30079. 3, 1,
  30080. 4, 2,
  30081. 4, 4,
  30082. 0, 2,
  30083. 1, 1,
  30084. 2, 2,
  30085. 3, 3,
  30086. 1, 3,
  30087. 2, 4 // 23: B + 12
  30088. ];
  30089. // Vertices[0, 1, ...9, A, B] : position on UV plane
  30090. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  30091. // First island of uv mapping
  30092. // v = 4h 3+ 2
  30093. // v = 3h 9+ 4
  30094. // v = 2h 9+ 5 B
  30095. // v = 1h 9 1 0
  30096. // v = 0h 3 8 7 A
  30097. // u = 0 1 2 3 4 5 6 *a
  30098. // Second island of uv mapping
  30099. // v = 4h 0+ B+ 4+
  30100. // v = 3h A+ 2+
  30101. // v = 2h 7+ 6 3+
  30102. // v = 1h 8+ 3+
  30103. // v = 0h
  30104. // u = 0 1 2 3 4 5 6 *a
  30105. // Face layout on texture UV mapping
  30106. // ============
  30107. // \ 4 /\ 16 / ======
  30108. // \ / \ / /\ 11 /
  30109. // \/ 7 \/ / \ /
  30110. // ======= / 10 \/
  30111. // /\ 17 /\ =======
  30112. // / \ / \ \ 15 /\
  30113. // / 8 \/ 12 \ \ / \
  30114. // ============ \/ 6 \
  30115. // \ 18 /\ ============
  30116. // \ / \ \ 5 /\ 0 /
  30117. // \/ 13 \ \ / \ /
  30118. // ======= \/ 1 \/
  30119. // =============
  30120. // /\ 19 /\ 2 /\
  30121. // / \ / \ / \
  30122. // / 14 \/ 9 \/ 3 \
  30123. // ===================
  30124. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  30125. var ustep = 138 / 1024;
  30126. var vstep = 239 / 1024;
  30127. var uoffset = 60 / 1024;
  30128. var voffset = 26 / 1024;
  30129. // Second island should have margin, not to touch the first island
  30130. // avoid any borderline artefact in pixel rounding
  30131. var island_u_offset = -40 / 1024;
  30132. var island_v_offset = +20 / 1024;
  30133. // face is either island 0 or 1 :
  30134. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  30135. var island = [
  30136. 0, 0, 0, 0, 1,
  30137. 0, 0, 1, 1, 0,
  30138. 0, 0, 1, 1, 0,
  30139. 0, 1, 1, 1, 0 // 15 - 19
  30140. ];
  30141. var indices = new Array();
  30142. var positions = new Array();
  30143. var normals = new Array();
  30144. var uvs = new Array();
  30145. var current_indice = 0;
  30146. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  30147. var face_vertex_pos = new Array(3);
  30148. var face_vertex_uv = new Array(3);
  30149. var v012;
  30150. for (v012 = 0; v012 < 3; v012++) {
  30151. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  30152. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  30153. }
  30154. // create all with normals
  30155. for (var face = 0; face < 20; face++) {
  30156. // 3 vertex per face
  30157. for (v012 = 0; v012 < 3; v012++) {
  30158. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  30159. var v_id = ico_indices[3 * face + v012];
  30160. // vertex have 3D position (x,y,z)
  30161. 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]);
  30162. // Normalize to get normal, then scale to radius
  30163. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  30164. // uv Coordinates from vertex ID
  30165. 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);
  30166. }
  30167. // Subdivide the face (interpolate pos, norm, uv)
  30168. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  30169. // - norm is linear interpolation of vertex corner normal
  30170. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  30171. // - uv is linear interpolation
  30172. //
  30173. // Topology is as below for sub-divide by 2
  30174. // vertex shown as v0,v1,v2
  30175. // interp index is i1 to progress in range [v0,v1[
  30176. // interp index is i2 to progress in range [v0,v2[
  30177. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  30178. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30179. //
  30180. //
  30181. // i2 v2
  30182. // ^ ^
  30183. // / / \
  30184. // / / \
  30185. // / / \
  30186. // / / (0,1) \
  30187. // / #---------\
  30188. // / / \ (0,0)'/ \
  30189. // / / \ / \
  30190. // / / \ / \
  30191. // / / (0,0) \ / (1,0) \
  30192. // / #---------#---------\
  30193. // v0 v1
  30194. //
  30195. // --------------------> i1
  30196. //
  30197. // interp of (i1,i2):
  30198. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  30199. // along i1 : lerp(x0,x1, i1/(S-i2))
  30200. //
  30201. // centroid of triangle is needed to get help normal computation
  30202. // (c1,c2) are used for centroid location
  30203. var interp_vertex = function (i1, i2, c1, c2) {
  30204. // vertex is interpolated from
  30205. // - face_vertex_pos[0..2]
  30206. // - face_vertex_uv[0..2]
  30207. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  30208. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  30209. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  30210. pos_interp.normalize();
  30211. var vertex_normal;
  30212. if (flat) {
  30213. // in flat mode, recalculate normal as face centroid normal
  30214. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  30215. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  30216. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  30217. }
  30218. else {
  30219. // in smooth mode, recalculate normal from each single vertex position
  30220. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  30221. }
  30222. // Vertex normal need correction due to X,Y,Z radius scaling
  30223. vertex_normal.x /= radiusX;
  30224. vertex_normal.y /= radiusY;
  30225. vertex_normal.z /= radiusZ;
  30226. vertex_normal.normalize();
  30227. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  30228. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  30229. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  30230. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  30231. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  30232. uvs.push(uv_interp.x, uv_interp.y);
  30233. // push each vertex has member of a face
  30234. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  30235. indices.push(current_indice);
  30236. current_indice++;
  30237. };
  30238. for (var i2 = 0; i2 < subdivisions; i2++) {
  30239. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  30240. // face : (i1,i2) for /\ :
  30241. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  30242. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30243. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30244. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30245. if (i1 + i2 + 1 < subdivisions) {
  30246. // face : (i1,i2)' for \/ :
  30247. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30248. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30249. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30250. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30251. }
  30252. }
  30253. }
  30254. }
  30255. // Sides
  30256. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30257. // Result
  30258. var vertexData = new VertexData();
  30259. vertexData.indices = indices;
  30260. vertexData.positions = positions;
  30261. vertexData.normals = normals;
  30262. vertexData.uvs = uvs;
  30263. return vertexData;
  30264. };
  30265. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  30266. /**
  30267. * Creates the VertexData of the Polyhedron.
  30268. */
  30269. VertexData.CreatePolyhedron = function (options) {
  30270. // provided polyhedron types :
  30271. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  30272. // 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)
  30273. var polyhedra = [];
  30274. 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]] };
  30275. 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]] };
  30276. polyhedra[2] = {
  30277. 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]],
  30278. 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]]
  30279. };
  30280. polyhedra[3] = {
  30281. 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]],
  30282. 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]]
  30283. };
  30284. polyhedra[4] = {
  30285. 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]],
  30286. 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]]
  30287. };
  30288. 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]] };
  30289. 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]] };
  30290. 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]] };
  30291. 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]] };
  30292. 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]] };
  30293. 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]] };
  30294. 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]] };
  30295. 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]] };
  30296. 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]] };
  30297. polyhedra[14] = {
  30298. 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]],
  30299. 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]]
  30300. };
  30301. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  30302. var size = options.size;
  30303. var sizeX = options.sizeX || size || 1;
  30304. var sizeY = options.sizeY || size || 1;
  30305. var sizeZ = options.sizeZ || size || 1;
  30306. var data = options.custom || polyhedra[type];
  30307. var nbfaces = data.face.length;
  30308. var faceUV = options.faceUV || new Array(nbfaces);
  30309. var faceColors = options.faceColors;
  30310. var flat = (options.flat === undefined) ? true : options.flat;
  30311. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30312. var positions = new Array();
  30313. var indices = new Array();
  30314. var normals = new Array();
  30315. var uvs = new Array();
  30316. var colors = new Array();
  30317. var index = 0;
  30318. var faceIdx = 0; // face cursor in the array "indexes"
  30319. var indexes = new Array();
  30320. var i = 0;
  30321. var f = 0;
  30322. var u, v, ang, x, y, tmp;
  30323. // default face colors and UV if undefined
  30324. if (flat) {
  30325. for (f = 0; f < nbfaces; f++) {
  30326. if (faceColors && faceColors[f] === undefined) {
  30327. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30328. }
  30329. if (faceUV && faceUV[f] === undefined) {
  30330. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30331. }
  30332. }
  30333. }
  30334. if (!flat) {
  30335. for (i = 0; i < data.vertex.length; i++) {
  30336. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  30337. uvs.push(0, 0);
  30338. }
  30339. for (f = 0; f < nbfaces; f++) {
  30340. for (i = 0; i < data.face[f].length - 2; i++) {
  30341. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  30342. }
  30343. }
  30344. }
  30345. else {
  30346. for (f = 0; f < nbfaces; f++) {
  30347. var fl = data.face[f].length; // number of vertices of the current face
  30348. ang = 2 * Math.PI / fl;
  30349. x = 0.5 * Math.tan(ang / 2);
  30350. y = 0.5;
  30351. // positions, uvs, colors
  30352. for (i = 0; i < fl; i++) {
  30353. // positions
  30354. 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);
  30355. indexes.push(index);
  30356. index++;
  30357. // uvs
  30358. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  30359. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  30360. uvs.push(u, v);
  30361. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  30362. y = x * Math.sin(ang) + y * Math.cos(ang);
  30363. x = tmp;
  30364. // colors
  30365. if (faceColors) {
  30366. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  30367. }
  30368. }
  30369. // indices from indexes
  30370. for (i = 0; i < fl - 2; i++) {
  30371. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  30372. }
  30373. faceIdx += fl;
  30374. }
  30375. }
  30376. VertexData.ComputeNormals(positions, indices, normals);
  30377. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30378. var vertexData = new VertexData();
  30379. vertexData.positions = positions;
  30380. vertexData.indices = indices;
  30381. vertexData.normals = normals;
  30382. vertexData.uvs = uvs;
  30383. if (faceColors && flat) {
  30384. vertexData.colors = colors;
  30385. }
  30386. return vertexData;
  30387. };
  30388. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  30389. /**
  30390. * Creates the VertexData of the Torus Knot.
  30391. */
  30392. VertexData.CreateTorusKnot = function (options) {
  30393. var indices = new Array();
  30394. var positions = new Array();
  30395. var normals = new Array();
  30396. var uvs = new Array();
  30397. var radius = options.radius || 2;
  30398. var tube = options.tube || 0.5;
  30399. var radialSegments = options.radialSegments || 32;
  30400. var tubularSegments = options.tubularSegments || 32;
  30401. var p = options.p || 2;
  30402. var q = options.q || 3;
  30403. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30404. // Helper
  30405. var getPos = function (angle) {
  30406. var cu = Math.cos(angle);
  30407. var su = Math.sin(angle);
  30408. var quOverP = q / p * angle;
  30409. var cs = Math.cos(quOverP);
  30410. var tx = radius * (2 + cs) * 0.5 * cu;
  30411. var ty = radius * (2 + cs) * su * 0.5;
  30412. var tz = radius * Math.sin(quOverP) * 0.5;
  30413. return new BABYLON.Vector3(tx, ty, tz);
  30414. };
  30415. // Vertices
  30416. var i;
  30417. var j;
  30418. for (i = 0; i <= radialSegments; i++) {
  30419. var modI = i % radialSegments;
  30420. var u = modI / radialSegments * 2 * p * Math.PI;
  30421. var p1 = getPos(u);
  30422. var p2 = getPos(u + 0.01);
  30423. var tang = p2.subtract(p1);
  30424. var n = p2.add(p1);
  30425. var bitan = BABYLON.Vector3.Cross(tang, n);
  30426. n = BABYLON.Vector3.Cross(bitan, tang);
  30427. bitan.normalize();
  30428. n.normalize();
  30429. for (j = 0; j < tubularSegments; j++) {
  30430. var modJ = j % tubularSegments;
  30431. var v = modJ / tubularSegments * 2 * Math.PI;
  30432. var cx = -tube * Math.cos(v);
  30433. var cy = tube * Math.sin(v);
  30434. positions.push(p1.x + cx * n.x + cy * bitan.x);
  30435. positions.push(p1.y + cx * n.y + cy * bitan.y);
  30436. positions.push(p1.z + cx * n.z + cy * bitan.z);
  30437. uvs.push(i / radialSegments);
  30438. uvs.push(j / tubularSegments);
  30439. }
  30440. }
  30441. for (i = 0; i < radialSegments; i++) {
  30442. for (j = 0; j < tubularSegments; j++) {
  30443. var jNext = (j + 1) % tubularSegments;
  30444. var a = i * tubularSegments + j;
  30445. var b = (i + 1) * tubularSegments + j;
  30446. var c = (i + 1) * tubularSegments + jNext;
  30447. var d = i * tubularSegments + jNext;
  30448. indices.push(d);
  30449. indices.push(b);
  30450. indices.push(a);
  30451. indices.push(d);
  30452. indices.push(c);
  30453. indices.push(b);
  30454. }
  30455. }
  30456. // Normals
  30457. VertexData.ComputeNormals(positions, indices, normals);
  30458. // Sides
  30459. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30460. // Result
  30461. var vertexData = new VertexData();
  30462. vertexData.indices = indices;
  30463. vertexData.positions = positions;
  30464. vertexData.normals = normals;
  30465. vertexData.uvs = uvs;
  30466. return vertexData;
  30467. };
  30468. // Tools
  30469. /**
  30470. * @param {any} - positions (number[] or Float32Array)
  30471. * @param {any} - indices (number[] or Uint16Array)
  30472. * @param {any} - normals (number[] or Float32Array)
  30473. * options (optional) :
  30474. * facetPositions : optional array of facet positions (vector3)
  30475. * facetNormals : optional array of facet normals (vector3)
  30476. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  30477. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  30478. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  30479. * bbSize : optional bounding box size data, required for facetPartitioning computation
  30480. * bInfo : optional bounding info, required for facetPartitioning computation
  30481. * useRightHandedSystem: optional boolean to for right handed system computation
  30482. * depthSort : optional boolean to enable the facet depth sort computation
  30483. * distanceTo : optional Vector3 to compute the facet depth from this location
  30484. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  30485. */
  30486. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  30487. // temporary scalar variables
  30488. var index = 0; // facet index
  30489. var p1p2x = 0.0; // p1p2 vector x coordinate
  30490. var p1p2y = 0.0; // p1p2 vector y coordinate
  30491. var p1p2z = 0.0; // p1p2 vector z coordinate
  30492. var p3p2x = 0.0; // p3p2 vector x coordinate
  30493. var p3p2y = 0.0; // p3p2 vector y coordinate
  30494. var p3p2z = 0.0; // p3p2 vector z coordinate
  30495. var faceNormalx = 0.0; // facet normal x coordinate
  30496. var faceNormaly = 0.0; // facet normal y coordinate
  30497. var faceNormalz = 0.0; // facet normal z coordinate
  30498. var length = 0.0; // facet normal length before normalization
  30499. var v1x = 0; // vector1 x index in the positions array
  30500. var v1y = 0; // vector1 y index in the positions array
  30501. var v1z = 0; // vector1 z index in the positions array
  30502. var v2x = 0; // vector2 x index in the positions array
  30503. var v2y = 0; // vector2 y index in the positions array
  30504. var v2z = 0; // vector2 z index in the positions array
  30505. var v3x = 0; // vector3 x index in the positions array
  30506. var v3y = 0; // vector3 y index in the positions array
  30507. var v3z = 0; // vector3 z index in the positions array
  30508. var computeFacetNormals = false;
  30509. var computeFacetPositions = false;
  30510. var computeFacetPartitioning = false;
  30511. var computeDepthSort = false;
  30512. var faceNormalSign = 1;
  30513. var ratio = 0;
  30514. var distanceTo = null;
  30515. if (options) {
  30516. computeFacetNormals = (options.facetNormals) ? true : false;
  30517. computeFacetPositions = (options.facetPositions) ? true : false;
  30518. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  30519. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  30520. ratio = options.ratio || 0;
  30521. computeDepthSort = (options.depthSort) ? true : false;
  30522. distanceTo = (options.distanceTo);
  30523. if (computeDepthSort) {
  30524. if (distanceTo === undefined) {
  30525. distanceTo = BABYLON.Vector3.Zero();
  30526. }
  30527. var depthSortedFacets = options.depthSortedFacets;
  30528. }
  30529. }
  30530. // facetPartitioning reinit if needed
  30531. var xSubRatio = 0;
  30532. var ySubRatio = 0;
  30533. var zSubRatio = 0;
  30534. var subSq = 0;
  30535. if (computeFacetPartitioning && options && options.bbSize) {
  30536. var ox = 0; // X partitioning index for facet position
  30537. var oy = 0; // Y partinioning index for facet position
  30538. var oz = 0; // Z partinioning index for facet position
  30539. var b1x = 0; // X partitioning index for facet v1 vertex
  30540. var b1y = 0; // Y partitioning index for facet v1 vertex
  30541. var b1z = 0; // z partitioning index for facet v1 vertex
  30542. var b2x = 0; // X partitioning index for facet v2 vertex
  30543. var b2y = 0; // Y partitioning index for facet v2 vertex
  30544. var b2z = 0; // Z partitioning index for facet v2 vertex
  30545. var b3x = 0; // X partitioning index for facet v3 vertex
  30546. var b3y = 0; // Y partitioning index for facet v3 vertex
  30547. var b3z = 0; // Z partitioning index for facet v3 vertex
  30548. var block_idx_o = 0; // facet barycenter block index
  30549. var block_idx_v1 = 0; // v1 vertex block index
  30550. var block_idx_v2 = 0; // v2 vertex block index
  30551. var block_idx_v3 = 0; // v3 vertex block index
  30552. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  30553. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  30554. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  30555. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  30556. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  30557. subSq = options.subDiv.max * options.subDiv.max;
  30558. options.facetPartitioning.length = 0;
  30559. }
  30560. // reset the normals
  30561. for (index = 0; index < positions.length; index++) {
  30562. normals[index] = 0.0;
  30563. }
  30564. // Loop : 1 indice triplet = 1 facet
  30565. var nbFaces = (indices.length / 3) | 0;
  30566. for (index = 0; index < nbFaces; index++) {
  30567. // get the indexes of the coordinates of each vertex of the facet
  30568. v1x = indices[index * 3] * 3;
  30569. v1y = v1x + 1;
  30570. v1z = v1x + 2;
  30571. v2x = indices[index * 3 + 1] * 3;
  30572. v2y = v2x + 1;
  30573. v2z = v2x + 2;
  30574. v3x = indices[index * 3 + 2] * 3;
  30575. v3y = v3x + 1;
  30576. v3z = v3x + 2;
  30577. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  30578. p1p2y = positions[v1y] - positions[v2y];
  30579. p1p2z = positions[v1z] - positions[v2z];
  30580. p3p2x = positions[v3x] - positions[v2x];
  30581. p3p2y = positions[v3y] - positions[v2y];
  30582. p3p2z = positions[v3z] - positions[v2z];
  30583. // compute the face normal with the cross product
  30584. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  30585. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  30586. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  30587. // normalize this normal and store it in the array facetData
  30588. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30589. length = (length === 0) ? 1.0 : length;
  30590. faceNormalx /= length;
  30591. faceNormaly /= length;
  30592. faceNormalz /= length;
  30593. if (computeFacetNormals && options) {
  30594. options.facetNormals[index].x = faceNormalx;
  30595. options.facetNormals[index].y = faceNormaly;
  30596. options.facetNormals[index].z = faceNormalz;
  30597. }
  30598. if (computeFacetPositions && options) {
  30599. // compute and the facet barycenter coordinates in the array facetPositions
  30600. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  30601. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  30602. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  30603. }
  30604. if (computeFacetPartitioning && options) {
  30605. // store the facet indexes in arrays in the main facetPartitioning array :
  30606. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  30607. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  30608. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  30609. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  30610. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30611. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30612. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30613. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30614. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30615. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30616. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30617. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30618. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30619. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  30620. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  30621. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  30622. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  30623. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  30624. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  30625. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  30626. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  30627. // push each facet index in each block containing the vertex
  30628. options.facetPartitioning[block_idx_v1].push(index);
  30629. if (block_idx_v2 != block_idx_v1) {
  30630. options.facetPartitioning[block_idx_v2].push(index);
  30631. }
  30632. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  30633. options.facetPartitioning[block_idx_v3].push(index);
  30634. }
  30635. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  30636. options.facetPartitioning[block_idx_o].push(index);
  30637. }
  30638. }
  30639. if (computeDepthSort && options && options.facetPositions) {
  30640. var dsf = depthSortedFacets[index];
  30641. dsf.ind = index * 3;
  30642. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  30643. }
  30644. // compute the normals anyway
  30645. normals[v1x] += faceNormalx; // accumulate all the normals per face
  30646. normals[v1y] += faceNormaly;
  30647. normals[v1z] += faceNormalz;
  30648. normals[v2x] += faceNormalx;
  30649. normals[v2y] += faceNormaly;
  30650. normals[v2z] += faceNormalz;
  30651. normals[v3x] += faceNormalx;
  30652. normals[v3y] += faceNormaly;
  30653. normals[v3z] += faceNormalz;
  30654. }
  30655. // last normalization of each normal
  30656. for (index = 0; index < normals.length / 3; index++) {
  30657. faceNormalx = normals[index * 3];
  30658. faceNormaly = normals[index * 3 + 1];
  30659. faceNormalz = normals[index * 3 + 2];
  30660. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30661. length = (length === 0) ? 1.0 : length;
  30662. faceNormalx /= length;
  30663. faceNormaly /= length;
  30664. faceNormalz /= length;
  30665. normals[index * 3] = faceNormalx;
  30666. normals[index * 3 + 1] = faceNormaly;
  30667. normals[index * 3 + 2] = faceNormalz;
  30668. }
  30669. };
  30670. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  30671. var li = indices.length;
  30672. var ln = normals.length;
  30673. var i;
  30674. var n;
  30675. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30676. switch (sideOrientation) {
  30677. case BABYLON.Mesh.FRONTSIDE:
  30678. // nothing changed
  30679. break;
  30680. case BABYLON.Mesh.BACKSIDE:
  30681. var tmp;
  30682. // indices
  30683. for (i = 0; i < li; i += 3) {
  30684. tmp = indices[i];
  30685. indices[i] = indices[i + 2];
  30686. indices[i + 2] = tmp;
  30687. }
  30688. // normals
  30689. for (n = 0; n < ln; n++) {
  30690. normals[n] = -normals[n];
  30691. }
  30692. break;
  30693. case BABYLON.Mesh.DOUBLESIDE:
  30694. // positions
  30695. var lp = positions.length;
  30696. var l = lp / 3;
  30697. for (var p = 0; p < lp; p++) {
  30698. positions[lp + p] = positions[p];
  30699. }
  30700. // indices
  30701. for (i = 0; i < li; i += 3) {
  30702. indices[i + li] = indices[i + 2] + l;
  30703. indices[i + 1 + li] = indices[i + 1] + l;
  30704. indices[i + 2 + li] = indices[i] + l;
  30705. }
  30706. // normals
  30707. for (n = 0; n < ln; n++) {
  30708. normals[ln + n] = -normals[n];
  30709. }
  30710. // uvs
  30711. var lu = uvs.length;
  30712. var u = 0;
  30713. for (u = 0; u < lu; u++) {
  30714. uvs[u + lu] = uvs[u];
  30715. }
  30716. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30717. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30718. u = 0;
  30719. for (i = 0; i < lu / 2; i++) {
  30720. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  30721. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  30722. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  30723. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  30724. u += 2;
  30725. }
  30726. break;
  30727. }
  30728. };
  30729. /**
  30730. * Creates a new VertexData from the imported parameters.
  30731. */
  30732. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  30733. var vertexData = new VertexData();
  30734. // positions
  30735. var positions = parsedVertexData.positions;
  30736. if (positions) {
  30737. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  30738. }
  30739. // normals
  30740. var normals = parsedVertexData.normals;
  30741. if (normals) {
  30742. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  30743. }
  30744. // tangents
  30745. var tangents = parsedVertexData.tangents;
  30746. if (tangents) {
  30747. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  30748. }
  30749. // uvs
  30750. var uvs = parsedVertexData.uvs;
  30751. if (uvs) {
  30752. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  30753. }
  30754. // uv2s
  30755. var uv2s = parsedVertexData.uv2s;
  30756. if (uv2s) {
  30757. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  30758. }
  30759. // uv3s
  30760. var uv3s = parsedVertexData.uv3s;
  30761. if (uv3s) {
  30762. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  30763. }
  30764. // uv4s
  30765. var uv4s = parsedVertexData.uv4s;
  30766. if (uv4s) {
  30767. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  30768. }
  30769. // uv5s
  30770. var uv5s = parsedVertexData.uv5s;
  30771. if (uv5s) {
  30772. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  30773. }
  30774. // uv6s
  30775. var uv6s = parsedVertexData.uv6s;
  30776. if (uv6s) {
  30777. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  30778. }
  30779. // colors
  30780. var colors = parsedVertexData.colors;
  30781. if (colors) {
  30782. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  30783. }
  30784. // matricesIndices
  30785. var matricesIndices = parsedVertexData.matricesIndices;
  30786. if (matricesIndices) {
  30787. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  30788. }
  30789. // matricesWeights
  30790. var matricesWeights = parsedVertexData.matricesWeights;
  30791. if (matricesWeights) {
  30792. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  30793. }
  30794. // indices
  30795. var indices = parsedVertexData.indices;
  30796. if (indices) {
  30797. vertexData.indices = indices;
  30798. }
  30799. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  30800. };
  30801. return VertexData;
  30802. }());
  30803. BABYLON.VertexData = VertexData;
  30804. })(BABYLON || (BABYLON = {}));
  30805. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  30806. var BABYLON;
  30807. (function (BABYLON) {
  30808. var Geometry = /** @class */ (function () {
  30809. function Geometry(id, scene, vertexData, updatable, mesh) {
  30810. if (updatable === void 0) { updatable = false; }
  30811. if (mesh === void 0) { mesh = null; }
  30812. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30813. this._totalVertices = 0;
  30814. this._isDisposed = false;
  30815. this._indexBufferIsUpdatable = false;
  30816. this.id = id;
  30817. this._engine = scene.getEngine();
  30818. this._meshes = [];
  30819. this._scene = scene;
  30820. //Init vertex buffer cache
  30821. this._vertexBuffers = {};
  30822. this._indices = [];
  30823. this._updatable = updatable;
  30824. // vertexData
  30825. if (vertexData) {
  30826. this.setAllVerticesData(vertexData, updatable);
  30827. }
  30828. else {
  30829. this._totalVertices = 0;
  30830. this._indices = [];
  30831. }
  30832. if (this._engine.getCaps().vertexArrayObject) {
  30833. this._vertexArrayObjects = {};
  30834. }
  30835. // applyToMesh
  30836. if (mesh) {
  30837. if (mesh.getClassName() === "LinesMesh") {
  30838. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  30839. this.updateExtend();
  30840. }
  30841. this.applyToMesh(mesh);
  30842. mesh.computeWorldMatrix(true);
  30843. }
  30844. }
  30845. Object.defineProperty(Geometry.prototype, "boundingBias", {
  30846. /**
  30847. * 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
  30848. * @returns The Bias Vector
  30849. */
  30850. get: function () {
  30851. return this._boundingBias;
  30852. },
  30853. set: function (value) {
  30854. if (this._boundingBias && this._boundingBias.equals(value)) {
  30855. return;
  30856. }
  30857. this._boundingBias = value.clone();
  30858. this.updateBoundingInfo(true, null);
  30859. },
  30860. enumerable: true,
  30861. configurable: true
  30862. });
  30863. Geometry.CreateGeometryForMesh = function (mesh) {
  30864. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  30865. geometry.applyToMesh(mesh);
  30866. return geometry;
  30867. };
  30868. Object.defineProperty(Geometry.prototype, "extend", {
  30869. get: function () {
  30870. return this._extend;
  30871. },
  30872. enumerable: true,
  30873. configurable: true
  30874. });
  30875. Geometry.prototype.getScene = function () {
  30876. return this._scene;
  30877. };
  30878. Geometry.prototype.getEngine = function () {
  30879. return this._engine;
  30880. };
  30881. Geometry.prototype.isReady = function () {
  30882. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  30883. };
  30884. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  30885. get: function () {
  30886. for (var index = 0; index < this._meshes.length; index++) {
  30887. if (!this._meshes[index].doNotSerialize) {
  30888. return false;
  30889. }
  30890. }
  30891. return true;
  30892. },
  30893. enumerable: true,
  30894. configurable: true
  30895. });
  30896. Geometry.prototype._rebuild = function () {
  30897. if (this._vertexArrayObjects) {
  30898. this._vertexArrayObjects = {};
  30899. }
  30900. // Index buffer
  30901. if (this._meshes.length !== 0 && this._indices) {
  30902. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30903. }
  30904. // Vertex buffers
  30905. for (var key in this._vertexBuffers) {
  30906. var vertexBuffer = this._vertexBuffers[key];
  30907. vertexBuffer._rebuild();
  30908. }
  30909. };
  30910. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  30911. vertexData.applyToGeometry(this, updatable);
  30912. this.notifyUpdate();
  30913. };
  30914. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  30915. if (updatable === void 0) { updatable = false; }
  30916. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  30917. this.setVerticesBuffer(buffer);
  30918. };
  30919. Geometry.prototype.removeVerticesData = function (kind) {
  30920. if (this._vertexBuffers[kind]) {
  30921. this._vertexBuffers[kind].dispose();
  30922. delete this._vertexBuffers[kind];
  30923. }
  30924. };
  30925. Geometry.prototype.setVerticesBuffer = function (buffer) {
  30926. var kind = buffer.getKind();
  30927. if (this._vertexBuffers[kind]) {
  30928. this._vertexBuffers[kind].dispose();
  30929. }
  30930. this._vertexBuffers[kind] = buffer;
  30931. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30932. var data = buffer.getData();
  30933. var stride = buffer.getStrideSize();
  30934. this._totalVertices = data.length / stride;
  30935. this.updateExtend(data, stride);
  30936. this._resetPointsArrayCache();
  30937. var meshes = this._meshes;
  30938. var numOfMeshes = meshes.length;
  30939. for (var index = 0; index < numOfMeshes; index++) {
  30940. var mesh = meshes[index];
  30941. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30942. mesh._createGlobalSubMesh(false);
  30943. mesh.computeWorldMatrix(true);
  30944. }
  30945. }
  30946. this.notifyUpdate(kind);
  30947. if (this._vertexArrayObjects) {
  30948. this._disposeVertexArrayObjects();
  30949. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  30950. }
  30951. };
  30952. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  30953. var vertexBuffer = this.getVertexBuffer(kind);
  30954. if (!vertexBuffer) {
  30955. return;
  30956. }
  30957. vertexBuffer.updateDirectly(data, offset);
  30958. this.notifyUpdate(kind);
  30959. };
  30960. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  30961. if (updateExtends === void 0) { updateExtends = false; }
  30962. var vertexBuffer = this.getVertexBuffer(kind);
  30963. if (!vertexBuffer) {
  30964. return;
  30965. }
  30966. vertexBuffer.update(data);
  30967. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30968. var stride = vertexBuffer.getStrideSize();
  30969. this._totalVertices = data.length / stride;
  30970. this.updateBoundingInfo(updateExtends, data);
  30971. }
  30972. this.notifyUpdate(kind);
  30973. };
  30974. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  30975. if (updateExtends) {
  30976. this.updateExtend(data);
  30977. }
  30978. var meshes = this._meshes;
  30979. var numOfMeshes = meshes.length;
  30980. this._resetPointsArrayCache();
  30981. for (var index = 0; index < numOfMeshes; index++) {
  30982. var mesh = meshes[index];
  30983. if (updateExtends) {
  30984. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30985. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  30986. var subMesh = mesh.subMeshes[subIndex];
  30987. subMesh.refreshBoundingInfo();
  30988. }
  30989. }
  30990. }
  30991. };
  30992. Geometry.prototype._bind = function (effect, indexToBind) {
  30993. if (!effect) {
  30994. return;
  30995. }
  30996. if (indexToBind === undefined) {
  30997. indexToBind = this._indexBuffer;
  30998. }
  30999. var vbs = this.getVertexBuffers();
  31000. if (!vbs) {
  31001. return;
  31002. }
  31003. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  31004. this._engine.bindBuffers(vbs, indexToBind, effect);
  31005. return;
  31006. }
  31007. // Using VAO
  31008. if (!this._vertexArrayObjects[effect.key]) {
  31009. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  31010. }
  31011. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  31012. };
  31013. Geometry.prototype.getTotalVertices = function () {
  31014. if (!this.isReady()) {
  31015. return 0;
  31016. }
  31017. return this._totalVertices;
  31018. };
  31019. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31020. var vertexBuffer = this.getVertexBuffer(kind);
  31021. if (!vertexBuffer) {
  31022. return null;
  31023. }
  31024. var orig = vertexBuffer.getData();
  31025. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  31026. return orig;
  31027. }
  31028. else {
  31029. var len = orig.length;
  31030. var copy = [];
  31031. for (var i = 0; i < len; i++) {
  31032. copy.push(orig[i]);
  31033. }
  31034. return copy;
  31035. }
  31036. };
  31037. /**
  31038. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31039. * Possible `kind` values :
  31040. * - BABYLON.VertexBuffer.PositionKind
  31041. * - BABYLON.VertexBuffer.UVKind
  31042. * - BABYLON.VertexBuffer.UV2Kind
  31043. * - BABYLON.VertexBuffer.UV3Kind
  31044. * - BABYLON.VertexBuffer.UV4Kind
  31045. * - BABYLON.VertexBuffer.UV5Kind
  31046. * - BABYLON.VertexBuffer.UV6Kind
  31047. * - BABYLON.VertexBuffer.ColorKind
  31048. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31049. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31050. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31051. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31052. */
  31053. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  31054. var vb = this._vertexBuffers[kind];
  31055. if (!vb) {
  31056. return false;
  31057. }
  31058. return vb.isUpdatable();
  31059. };
  31060. Geometry.prototype.getVertexBuffer = function (kind) {
  31061. if (!this.isReady()) {
  31062. return null;
  31063. }
  31064. return this._vertexBuffers[kind];
  31065. };
  31066. Geometry.prototype.getVertexBuffers = function () {
  31067. if (!this.isReady()) {
  31068. return null;
  31069. }
  31070. return this._vertexBuffers;
  31071. };
  31072. Geometry.prototype.isVerticesDataPresent = function (kind) {
  31073. if (!this._vertexBuffers) {
  31074. if (this._delayInfo) {
  31075. return this._delayInfo.indexOf(kind) !== -1;
  31076. }
  31077. return false;
  31078. }
  31079. return this._vertexBuffers[kind] !== undefined;
  31080. };
  31081. Geometry.prototype.getVerticesDataKinds = function () {
  31082. var result = [];
  31083. var kind;
  31084. if (!this._vertexBuffers && this._delayInfo) {
  31085. for (kind in this._delayInfo) {
  31086. result.push(kind);
  31087. }
  31088. }
  31089. else {
  31090. for (kind in this._vertexBuffers) {
  31091. result.push(kind);
  31092. }
  31093. }
  31094. return result;
  31095. };
  31096. Geometry.prototype.updateIndices = function (indices, offset) {
  31097. if (!this._indexBuffer) {
  31098. return;
  31099. }
  31100. if (!this._indexBufferIsUpdatable) {
  31101. this.setIndices(indices, null, true);
  31102. }
  31103. else {
  31104. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  31105. }
  31106. };
  31107. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  31108. if (totalVertices === void 0) { totalVertices = null; }
  31109. if (updatable === void 0) { updatable = false; }
  31110. if (this._indexBuffer) {
  31111. this._engine._releaseBuffer(this._indexBuffer);
  31112. }
  31113. this._disposeVertexArrayObjects();
  31114. this._indices = indices;
  31115. this._indexBufferIsUpdatable = updatable;
  31116. if (this._meshes.length !== 0 && this._indices) {
  31117. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  31118. }
  31119. if (totalVertices != undefined) {
  31120. this._totalVertices = totalVertices;
  31121. }
  31122. var meshes = this._meshes;
  31123. var numOfMeshes = meshes.length;
  31124. for (var index = 0; index < numOfMeshes; index++) {
  31125. meshes[index]._createGlobalSubMesh(true);
  31126. }
  31127. this.notifyUpdate();
  31128. };
  31129. Geometry.prototype.getTotalIndices = function () {
  31130. if (!this.isReady()) {
  31131. return 0;
  31132. }
  31133. return this._indices.length;
  31134. };
  31135. Geometry.prototype.getIndices = function (copyWhenShared) {
  31136. if (!this.isReady()) {
  31137. return null;
  31138. }
  31139. var orig = this._indices;
  31140. if (!copyWhenShared || this._meshes.length === 1) {
  31141. return orig;
  31142. }
  31143. else {
  31144. var len = orig.length;
  31145. var copy = [];
  31146. for (var i = 0; i < len; i++) {
  31147. copy.push(orig[i]);
  31148. }
  31149. return copy;
  31150. }
  31151. };
  31152. Geometry.prototype.getIndexBuffer = function () {
  31153. if (!this.isReady()) {
  31154. return null;
  31155. }
  31156. return this._indexBuffer;
  31157. };
  31158. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  31159. if (effect === void 0) { effect = null; }
  31160. if (!effect || !this._vertexArrayObjects) {
  31161. return;
  31162. }
  31163. if (this._vertexArrayObjects[effect.key]) {
  31164. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  31165. delete this._vertexArrayObjects[effect.key];
  31166. }
  31167. };
  31168. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  31169. var meshes = this._meshes;
  31170. var index = meshes.indexOf(mesh);
  31171. if (index === -1) {
  31172. return;
  31173. }
  31174. meshes.splice(index, 1);
  31175. mesh._geometry = null;
  31176. if (meshes.length === 0 && shouldDispose) {
  31177. this.dispose();
  31178. }
  31179. };
  31180. Geometry.prototype.applyToMesh = function (mesh) {
  31181. if (mesh._geometry === this) {
  31182. return;
  31183. }
  31184. var previousGeometry = mesh._geometry;
  31185. if (previousGeometry) {
  31186. previousGeometry.releaseForMesh(mesh);
  31187. }
  31188. var meshes = this._meshes;
  31189. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  31190. mesh._geometry = this;
  31191. this._scene.pushGeometry(this);
  31192. meshes.push(mesh);
  31193. if (this.isReady()) {
  31194. this._applyToMesh(mesh);
  31195. }
  31196. else {
  31197. mesh._boundingInfo = this._boundingInfo;
  31198. }
  31199. };
  31200. Geometry.prototype.updateExtend = function (data, stride) {
  31201. if (data === void 0) { data = null; }
  31202. if (!data) {
  31203. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  31204. }
  31205. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  31206. };
  31207. Geometry.prototype._applyToMesh = function (mesh) {
  31208. var numOfMeshes = this._meshes.length;
  31209. // vertexBuffers
  31210. for (var kind in this._vertexBuffers) {
  31211. if (numOfMeshes === 1) {
  31212. this._vertexBuffers[kind].create();
  31213. }
  31214. var buffer = this._vertexBuffers[kind].getBuffer();
  31215. if (buffer)
  31216. buffer.references = numOfMeshes;
  31217. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31218. if (!this._extend) {
  31219. this.updateExtend(this._vertexBuffers[kind].getData());
  31220. }
  31221. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31222. mesh._createGlobalSubMesh(false);
  31223. //bounding info was just created again, world matrix should be applied again.
  31224. mesh._updateBoundingInfo();
  31225. }
  31226. }
  31227. // indexBuffer
  31228. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  31229. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31230. }
  31231. if (this._indexBuffer) {
  31232. this._indexBuffer.references = numOfMeshes;
  31233. }
  31234. };
  31235. Geometry.prototype.notifyUpdate = function (kind) {
  31236. if (this.onGeometryUpdated) {
  31237. this.onGeometryUpdated(this, kind);
  31238. }
  31239. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  31240. var mesh = _a[_i];
  31241. mesh._markSubMeshesAsAttributesDirty();
  31242. }
  31243. };
  31244. Geometry.prototype.load = function (scene, onLoaded) {
  31245. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31246. return;
  31247. }
  31248. if (this.isReady()) {
  31249. if (onLoaded) {
  31250. onLoaded();
  31251. }
  31252. return;
  31253. }
  31254. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31255. this._queueLoad(scene, onLoaded);
  31256. };
  31257. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  31258. var _this = this;
  31259. if (!this.delayLoadingFile) {
  31260. return;
  31261. }
  31262. scene._addPendingData(this);
  31263. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31264. if (!_this._delayLoadingFunction) {
  31265. return;
  31266. }
  31267. _this._delayLoadingFunction(JSON.parse(data), _this);
  31268. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31269. _this._delayInfo = [];
  31270. scene._removePendingData(_this);
  31271. var meshes = _this._meshes;
  31272. var numOfMeshes = meshes.length;
  31273. for (var index = 0; index < numOfMeshes; index++) {
  31274. _this._applyToMesh(meshes[index]);
  31275. }
  31276. if (onLoaded) {
  31277. onLoaded();
  31278. }
  31279. }, function () { }, scene.database);
  31280. };
  31281. /**
  31282. * Invert the geometry to move from a right handed system to a left handed one.
  31283. */
  31284. Geometry.prototype.toLeftHanded = function () {
  31285. // Flip faces
  31286. var tIndices = this.getIndices(false);
  31287. if (tIndices != null && tIndices.length > 0) {
  31288. for (var i = 0; i < tIndices.length; i += 3) {
  31289. var tTemp = tIndices[i + 0];
  31290. tIndices[i + 0] = tIndices[i + 2];
  31291. tIndices[i + 2] = tTemp;
  31292. }
  31293. this.setIndices(tIndices);
  31294. }
  31295. // Negate position.z
  31296. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  31297. if (tPositions != null && tPositions.length > 0) {
  31298. for (var i = 0; i < tPositions.length; i += 3) {
  31299. tPositions[i + 2] = -tPositions[i + 2];
  31300. }
  31301. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  31302. }
  31303. // Negate normal.z
  31304. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  31305. if (tNormals != null && tNormals.length > 0) {
  31306. for (var i = 0; i < tNormals.length; i += 3) {
  31307. tNormals[i + 2] = -tNormals[i + 2];
  31308. }
  31309. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  31310. }
  31311. };
  31312. // Cache
  31313. Geometry.prototype._resetPointsArrayCache = function () {
  31314. this._positions = null;
  31315. };
  31316. Geometry.prototype._generatePointsArray = function () {
  31317. if (this._positions)
  31318. return true;
  31319. this._positions = [];
  31320. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31321. if (!data) {
  31322. return false;
  31323. }
  31324. for (var index = 0; index < data.length; index += 3) {
  31325. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  31326. }
  31327. return true;
  31328. };
  31329. Geometry.prototype.isDisposed = function () {
  31330. return this._isDisposed;
  31331. };
  31332. Geometry.prototype._disposeVertexArrayObjects = function () {
  31333. if (this._vertexArrayObjects) {
  31334. for (var kind in this._vertexArrayObjects) {
  31335. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  31336. }
  31337. this._vertexArrayObjects = {};
  31338. }
  31339. };
  31340. Geometry.prototype.dispose = function () {
  31341. var meshes = this._meshes;
  31342. var numOfMeshes = meshes.length;
  31343. var index;
  31344. for (index = 0; index < numOfMeshes; index++) {
  31345. this.releaseForMesh(meshes[index]);
  31346. }
  31347. this._meshes = [];
  31348. this._disposeVertexArrayObjects();
  31349. for (var kind in this._vertexBuffers) {
  31350. this._vertexBuffers[kind].dispose();
  31351. }
  31352. this._vertexBuffers = {};
  31353. this._totalVertices = 0;
  31354. if (this._indexBuffer) {
  31355. this._engine._releaseBuffer(this._indexBuffer);
  31356. }
  31357. this._indexBuffer = null;
  31358. this._indices = [];
  31359. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31360. this.delayLoadingFile = null;
  31361. this._delayLoadingFunction = null;
  31362. this._delayInfo = [];
  31363. this._boundingInfo = null;
  31364. this._scene.removeGeometry(this);
  31365. this._isDisposed = true;
  31366. };
  31367. Geometry.prototype.copy = function (id) {
  31368. var vertexData = new BABYLON.VertexData();
  31369. vertexData.indices = [];
  31370. var indices = this.getIndices();
  31371. if (indices) {
  31372. for (var index = 0; index < indices.length; index++) {
  31373. vertexData.indices.push(indices[index]);
  31374. }
  31375. }
  31376. var updatable = false;
  31377. var stopChecking = false;
  31378. var kind;
  31379. for (kind in this._vertexBuffers) {
  31380. // using slice() to make a copy of the array and not just reference it
  31381. var data = this.getVerticesData(kind);
  31382. if (data instanceof Float32Array) {
  31383. vertexData.set(new Float32Array(data), kind);
  31384. }
  31385. else {
  31386. vertexData.set(data.slice(0), kind);
  31387. }
  31388. if (!stopChecking) {
  31389. var vb = this.getVertexBuffer(kind);
  31390. if (vb) {
  31391. updatable = vb.isUpdatable();
  31392. stopChecking = !updatable;
  31393. }
  31394. }
  31395. }
  31396. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  31397. geometry.delayLoadState = this.delayLoadState;
  31398. geometry.delayLoadingFile = this.delayLoadingFile;
  31399. geometry._delayLoadingFunction = this._delayLoadingFunction;
  31400. for (kind in this._delayInfo) {
  31401. geometry._delayInfo = geometry._delayInfo || [];
  31402. geometry._delayInfo.push(kind);
  31403. }
  31404. // Bounding info
  31405. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31406. return geometry;
  31407. };
  31408. Geometry.prototype.serialize = function () {
  31409. var serializationObject = {};
  31410. serializationObject.id = this.id;
  31411. serializationObject.updatable = this._updatable;
  31412. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  31413. serializationObject.tags = BABYLON.Tags.GetTags(this);
  31414. }
  31415. return serializationObject;
  31416. };
  31417. Geometry.prototype.toNumberArray = function (origin) {
  31418. if (Array.isArray(origin)) {
  31419. return origin;
  31420. }
  31421. else {
  31422. return Array.prototype.slice.call(origin);
  31423. }
  31424. };
  31425. Geometry.prototype.serializeVerticeData = function () {
  31426. var serializationObject = this.serialize();
  31427. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31428. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  31429. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  31430. serializationObject.positions._updatable = true;
  31431. }
  31432. }
  31433. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31434. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  31435. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  31436. serializationObject.normals._updatable = true;
  31437. }
  31438. }
  31439. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31440. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  31441. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  31442. serializationObject.uvs._updatable = true;
  31443. }
  31444. }
  31445. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31446. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  31447. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  31448. serializationObject.uv2s._updatable = true;
  31449. }
  31450. }
  31451. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31452. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  31453. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  31454. serializationObject.uv3s._updatable = true;
  31455. }
  31456. }
  31457. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31458. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  31459. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  31460. serializationObject.uv4s._updatable = true;
  31461. }
  31462. }
  31463. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31464. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  31465. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  31466. serializationObject.uv5s._updatable = true;
  31467. }
  31468. }
  31469. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31470. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  31471. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  31472. serializationObject.uv6s._updatable = true;
  31473. }
  31474. }
  31475. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31476. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  31477. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  31478. serializationObject.colors._updatable = true;
  31479. }
  31480. }
  31481. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31482. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  31483. serializationObject.matricesIndices._isExpanded = true;
  31484. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31485. serializationObject.matricesIndices._updatable = true;
  31486. }
  31487. }
  31488. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31489. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  31490. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31491. serializationObject.matricesWeights._updatable = true;
  31492. }
  31493. }
  31494. serializationObject.indices = this.toNumberArray(this.getIndices());
  31495. return serializationObject;
  31496. };
  31497. // Statics
  31498. Geometry.ExtractFromMesh = function (mesh, id) {
  31499. var geometry = mesh._geometry;
  31500. if (!geometry) {
  31501. return null;
  31502. }
  31503. return geometry.copy(id);
  31504. };
  31505. /**
  31506. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  31507. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  31508. * Be aware Math.random() could cause collisions, but:
  31509. * "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"
  31510. */
  31511. Geometry.RandomId = function () {
  31512. return BABYLON.Tools.RandomId();
  31513. };
  31514. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  31515. var scene = mesh.getScene();
  31516. // Geometry
  31517. var geometryId = parsedGeometry.geometryId;
  31518. if (geometryId) {
  31519. var geometry = scene.getGeometryByID(geometryId);
  31520. if (geometry) {
  31521. geometry.applyToMesh(mesh);
  31522. }
  31523. }
  31524. else if (parsedGeometry instanceof ArrayBuffer) {
  31525. var binaryInfo = mesh._binaryInfo;
  31526. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  31527. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  31528. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  31529. }
  31530. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  31531. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  31532. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  31533. }
  31534. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  31535. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  31536. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  31537. }
  31538. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  31539. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  31540. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  31541. }
  31542. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  31543. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  31544. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  31545. }
  31546. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  31547. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  31548. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  31549. }
  31550. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  31551. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  31552. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  31553. }
  31554. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  31555. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  31556. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  31557. }
  31558. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  31559. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  31560. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  31561. }
  31562. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  31563. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  31564. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  31565. }
  31566. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  31567. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  31568. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  31569. }
  31570. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  31571. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  31572. mesh.setIndices(indicesData, null);
  31573. }
  31574. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  31575. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  31576. mesh.subMeshes = [];
  31577. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  31578. var materialIndex = subMeshesData[(i * 5) + 0];
  31579. var verticesStart = subMeshesData[(i * 5) + 1];
  31580. var verticesCount = subMeshesData[(i * 5) + 2];
  31581. var indexStart = subMeshesData[(i * 5) + 3];
  31582. var indexCount = subMeshesData[(i * 5) + 4];
  31583. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  31584. }
  31585. }
  31586. }
  31587. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  31588. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  31589. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  31590. if (parsedGeometry.uvs) {
  31591. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  31592. }
  31593. if (parsedGeometry.uvs2) {
  31594. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  31595. }
  31596. if (parsedGeometry.uvs3) {
  31597. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  31598. }
  31599. if (parsedGeometry.uvs4) {
  31600. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  31601. }
  31602. if (parsedGeometry.uvs5) {
  31603. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  31604. }
  31605. if (parsedGeometry.uvs6) {
  31606. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  31607. }
  31608. if (parsedGeometry.colors) {
  31609. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  31610. }
  31611. if (parsedGeometry.matricesIndices) {
  31612. if (!parsedGeometry.matricesIndices._isExpanded) {
  31613. var floatIndices = [];
  31614. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  31615. var matricesIndex = parsedGeometry.matricesIndices[i];
  31616. floatIndices.push(matricesIndex & 0x000000FF);
  31617. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31618. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31619. floatIndices.push(matricesIndex >> 24);
  31620. }
  31621. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  31622. }
  31623. else {
  31624. delete parsedGeometry.matricesIndices._isExpanded;
  31625. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  31626. }
  31627. }
  31628. if (parsedGeometry.matricesIndicesExtra) {
  31629. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  31630. var floatIndices = [];
  31631. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  31632. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  31633. floatIndices.push(matricesIndex & 0x000000FF);
  31634. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31635. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31636. floatIndices.push(matricesIndex >> 24);
  31637. }
  31638. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  31639. }
  31640. else {
  31641. delete parsedGeometry.matricesIndices._isExpanded;
  31642. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  31643. }
  31644. }
  31645. if (parsedGeometry.matricesWeights) {
  31646. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  31647. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  31648. }
  31649. if (parsedGeometry.matricesWeightsExtra) {
  31650. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  31651. }
  31652. mesh.setIndices(parsedGeometry.indices, null);
  31653. }
  31654. // SubMeshes
  31655. if (parsedGeometry.subMeshes) {
  31656. mesh.subMeshes = [];
  31657. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  31658. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  31659. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  31660. }
  31661. }
  31662. // Flat shading
  31663. if (mesh._shouldGenerateFlatShading) {
  31664. mesh.convertToFlatShadedMesh();
  31665. delete mesh._shouldGenerateFlatShading;
  31666. }
  31667. // Update
  31668. mesh.computeWorldMatrix(true);
  31669. // Octree
  31670. if (scene['_selectionOctree']) {
  31671. scene['_selectionOctree'].addMesh(mesh);
  31672. }
  31673. };
  31674. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  31675. var epsilon = 1e-3;
  31676. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  31677. return;
  31678. }
  31679. var noInfluenceBoneIndex = 0.0;
  31680. if (parsedGeometry.skeletonId > -1) {
  31681. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  31682. if (!skeleton) {
  31683. return;
  31684. }
  31685. noInfluenceBoneIndex = skeleton.bones.length;
  31686. }
  31687. else {
  31688. return;
  31689. }
  31690. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31691. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31692. var matricesWeights = parsedGeometry.matricesWeights;
  31693. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  31694. var influencers = parsedGeometry.numBoneInfluencer;
  31695. var size = matricesWeights.length;
  31696. for (var i = 0; i < size; i += 4) {
  31697. var weight = 0.0;
  31698. var firstZeroWeight = -1;
  31699. for (var j = 0; j < 4; j++) {
  31700. var w = matricesWeights[i + j];
  31701. weight += w;
  31702. if (w < epsilon && firstZeroWeight < 0) {
  31703. firstZeroWeight = j;
  31704. }
  31705. }
  31706. if (matricesWeightsExtra) {
  31707. for (var j = 0; j < 4; j++) {
  31708. var w = matricesWeightsExtra[i + j];
  31709. weight += w;
  31710. if (w < epsilon && firstZeroWeight < 0) {
  31711. firstZeroWeight = j + 4;
  31712. }
  31713. }
  31714. }
  31715. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  31716. firstZeroWeight = influencers - 1;
  31717. }
  31718. if (weight > epsilon) {
  31719. var mweight = 1.0 / weight;
  31720. for (var j = 0; j < 4; j++) {
  31721. matricesWeights[i + j] *= mweight;
  31722. }
  31723. if (matricesWeightsExtra) {
  31724. for (var j = 0; j < 4; j++) {
  31725. matricesWeightsExtra[i + j] *= mweight;
  31726. }
  31727. }
  31728. }
  31729. else {
  31730. if (firstZeroWeight >= 4) {
  31731. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  31732. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  31733. }
  31734. else {
  31735. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  31736. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  31737. }
  31738. }
  31739. }
  31740. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  31741. if (parsedGeometry.matricesWeightsExtra) {
  31742. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  31743. }
  31744. };
  31745. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  31746. if (scene.getGeometryByID(parsedVertexData.id)) {
  31747. return null; // null since geometry could be something else than a box...
  31748. }
  31749. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  31750. if (BABYLON.Tags) {
  31751. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  31752. }
  31753. if (parsedVertexData.delayLoadingFile) {
  31754. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31755. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  31756. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  31757. geometry._delayInfo = [];
  31758. if (parsedVertexData.hasUVs) {
  31759. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  31760. }
  31761. if (parsedVertexData.hasUVs2) {
  31762. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  31763. }
  31764. if (parsedVertexData.hasUVs3) {
  31765. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  31766. }
  31767. if (parsedVertexData.hasUVs4) {
  31768. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  31769. }
  31770. if (parsedVertexData.hasUVs5) {
  31771. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  31772. }
  31773. if (parsedVertexData.hasUVs6) {
  31774. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  31775. }
  31776. if (parsedVertexData.hasColors) {
  31777. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  31778. }
  31779. if (parsedVertexData.hasMatricesIndices) {
  31780. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31781. }
  31782. if (parsedVertexData.hasMatricesWeights) {
  31783. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31784. }
  31785. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  31786. }
  31787. else {
  31788. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  31789. }
  31790. scene.pushGeometry(geometry, true);
  31791. return geometry;
  31792. };
  31793. return Geometry;
  31794. }());
  31795. BABYLON.Geometry = Geometry;
  31796. /////// Primitives //////////////////////////////////////////////
  31797. (function (Geometry) {
  31798. var Primitives;
  31799. (function (Primitives) {
  31800. /// Abstract class
  31801. var _Primitive = /** @class */ (function (_super) {
  31802. __extends(_Primitive, _super);
  31803. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  31804. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  31805. if (mesh === void 0) { mesh = null; }
  31806. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  31807. _this._canBeRegenerated = _canBeRegenerated;
  31808. _this._beingRegenerated = true;
  31809. _this.regenerate();
  31810. _this._beingRegenerated = false;
  31811. return _this;
  31812. }
  31813. _Primitive.prototype.canBeRegenerated = function () {
  31814. return this._canBeRegenerated;
  31815. };
  31816. _Primitive.prototype.regenerate = function () {
  31817. if (!this._canBeRegenerated) {
  31818. return;
  31819. }
  31820. this._beingRegenerated = true;
  31821. this.setAllVerticesData(this._regenerateVertexData(), false);
  31822. this._beingRegenerated = false;
  31823. };
  31824. _Primitive.prototype.asNewGeometry = function (id) {
  31825. return _super.prototype.copy.call(this, id);
  31826. };
  31827. // overrides
  31828. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  31829. if (!this._beingRegenerated) {
  31830. return;
  31831. }
  31832. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  31833. };
  31834. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  31835. if (!this._beingRegenerated) {
  31836. return;
  31837. }
  31838. _super.prototype.setVerticesData.call(this, kind, data, false);
  31839. };
  31840. // to override
  31841. // protected
  31842. _Primitive.prototype._regenerateVertexData = function () {
  31843. throw new Error("Abstract method");
  31844. };
  31845. _Primitive.prototype.copy = function (id) {
  31846. throw new Error("Must be overriden in sub-classes.");
  31847. };
  31848. _Primitive.prototype.serialize = function () {
  31849. var serializationObject = _super.prototype.serialize.call(this);
  31850. serializationObject.canBeRegenerated = this.canBeRegenerated();
  31851. return serializationObject;
  31852. };
  31853. return _Primitive;
  31854. }(Geometry));
  31855. Primitives._Primitive = _Primitive;
  31856. var Ribbon = /** @class */ (function (_super) {
  31857. __extends(Ribbon, _super);
  31858. // Members
  31859. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  31860. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31861. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31862. _this.pathArray = pathArray;
  31863. _this.closeArray = closeArray;
  31864. _this.closePath = closePath;
  31865. _this.offset = offset;
  31866. _this.side = side;
  31867. return _this;
  31868. }
  31869. Ribbon.prototype._regenerateVertexData = function () {
  31870. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  31871. };
  31872. Ribbon.prototype.copy = function (id) {
  31873. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  31874. };
  31875. return Ribbon;
  31876. }(_Primitive));
  31877. Primitives.Ribbon = Ribbon;
  31878. var Box = /** @class */ (function (_super) {
  31879. __extends(Box, _super);
  31880. // Members
  31881. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  31882. if (mesh === void 0) { mesh = null; }
  31883. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31884. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31885. _this.size = size;
  31886. _this.side = side;
  31887. return _this;
  31888. }
  31889. Box.prototype._regenerateVertexData = function () {
  31890. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  31891. };
  31892. Box.prototype.copy = function (id) {
  31893. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  31894. };
  31895. Box.prototype.serialize = function () {
  31896. var serializationObject = _super.prototype.serialize.call(this);
  31897. serializationObject.size = this.size;
  31898. return serializationObject;
  31899. };
  31900. Box.Parse = function (parsedBox, scene) {
  31901. if (scene.getGeometryByID(parsedBox.id)) {
  31902. return null; // null since geometry could be something else than a box...
  31903. }
  31904. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  31905. if (BABYLON.Tags) {
  31906. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  31907. }
  31908. scene.pushGeometry(box, true);
  31909. return box;
  31910. };
  31911. return Box;
  31912. }(_Primitive));
  31913. Primitives.Box = Box;
  31914. var Sphere = /** @class */ (function (_super) {
  31915. __extends(Sphere, _super);
  31916. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  31917. if (mesh === void 0) { mesh = null; }
  31918. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31919. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31920. _this.segments = segments;
  31921. _this.diameter = diameter;
  31922. _this.side = side;
  31923. return _this;
  31924. }
  31925. Sphere.prototype._regenerateVertexData = function () {
  31926. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  31927. };
  31928. Sphere.prototype.copy = function (id) {
  31929. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  31930. };
  31931. Sphere.prototype.serialize = function () {
  31932. var serializationObject = _super.prototype.serialize.call(this);
  31933. serializationObject.segments = this.segments;
  31934. serializationObject.diameter = this.diameter;
  31935. return serializationObject;
  31936. };
  31937. Sphere.Parse = function (parsedSphere, scene) {
  31938. if (scene.getGeometryByID(parsedSphere.id)) {
  31939. return null; // null since geometry could be something else than a sphere...
  31940. }
  31941. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  31942. if (BABYLON.Tags) {
  31943. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  31944. }
  31945. scene.pushGeometry(sphere, true);
  31946. return sphere;
  31947. };
  31948. return Sphere;
  31949. }(_Primitive));
  31950. Primitives.Sphere = Sphere;
  31951. var Disc = /** @class */ (function (_super) {
  31952. __extends(Disc, _super);
  31953. // Members
  31954. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  31955. if (mesh === void 0) { mesh = null; }
  31956. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31957. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31958. _this.radius = radius;
  31959. _this.tessellation = tessellation;
  31960. _this.side = side;
  31961. return _this;
  31962. }
  31963. Disc.prototype._regenerateVertexData = function () {
  31964. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  31965. };
  31966. Disc.prototype.copy = function (id) {
  31967. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  31968. };
  31969. return Disc;
  31970. }(_Primitive));
  31971. Primitives.Disc = Disc;
  31972. var Cylinder = /** @class */ (function (_super) {
  31973. __extends(Cylinder, _super);
  31974. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  31975. if (subdivisions === void 0) { subdivisions = 1; }
  31976. if (mesh === void 0) { mesh = null; }
  31977. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31978. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31979. _this.height = height;
  31980. _this.diameterTop = diameterTop;
  31981. _this.diameterBottom = diameterBottom;
  31982. _this.tessellation = tessellation;
  31983. _this.subdivisions = subdivisions;
  31984. _this.side = side;
  31985. return _this;
  31986. }
  31987. Cylinder.prototype._regenerateVertexData = function () {
  31988. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  31989. };
  31990. Cylinder.prototype.copy = function (id) {
  31991. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  31992. };
  31993. Cylinder.prototype.serialize = function () {
  31994. var serializationObject = _super.prototype.serialize.call(this);
  31995. serializationObject.height = this.height;
  31996. serializationObject.diameterTop = this.diameterTop;
  31997. serializationObject.diameterBottom = this.diameterBottom;
  31998. serializationObject.tessellation = this.tessellation;
  31999. return serializationObject;
  32000. };
  32001. Cylinder.Parse = function (parsedCylinder, scene) {
  32002. if (scene.getGeometryByID(parsedCylinder.id)) {
  32003. return null; // null since geometry could be something else than a cylinder...
  32004. }
  32005. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  32006. if (BABYLON.Tags) {
  32007. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  32008. }
  32009. scene.pushGeometry(cylinder, true);
  32010. return cylinder;
  32011. };
  32012. return Cylinder;
  32013. }(_Primitive));
  32014. Primitives.Cylinder = Cylinder;
  32015. var Torus = /** @class */ (function (_super) {
  32016. __extends(Torus, _super);
  32017. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  32018. if (mesh === void 0) { mesh = null; }
  32019. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32020. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32021. _this.diameter = diameter;
  32022. _this.thickness = thickness;
  32023. _this.tessellation = tessellation;
  32024. _this.side = side;
  32025. return _this;
  32026. }
  32027. Torus.prototype._regenerateVertexData = function () {
  32028. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  32029. };
  32030. Torus.prototype.copy = function (id) {
  32031. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  32032. };
  32033. Torus.prototype.serialize = function () {
  32034. var serializationObject = _super.prototype.serialize.call(this);
  32035. serializationObject.diameter = this.diameter;
  32036. serializationObject.thickness = this.thickness;
  32037. serializationObject.tessellation = this.tessellation;
  32038. return serializationObject;
  32039. };
  32040. Torus.Parse = function (parsedTorus, scene) {
  32041. if (scene.getGeometryByID(parsedTorus.id)) {
  32042. return null; // null since geometry could be something else than a torus...
  32043. }
  32044. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  32045. if (BABYLON.Tags) {
  32046. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  32047. }
  32048. scene.pushGeometry(torus, true);
  32049. return torus;
  32050. };
  32051. return Torus;
  32052. }(_Primitive));
  32053. Primitives.Torus = Torus;
  32054. var Ground = /** @class */ (function (_super) {
  32055. __extends(Ground, _super);
  32056. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  32057. if (mesh === void 0) { mesh = null; }
  32058. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32059. _this.width = width;
  32060. _this.height = height;
  32061. _this.subdivisions = subdivisions;
  32062. return _this;
  32063. }
  32064. Ground.prototype._regenerateVertexData = function () {
  32065. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  32066. };
  32067. Ground.prototype.copy = function (id) {
  32068. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  32069. };
  32070. Ground.prototype.serialize = function () {
  32071. var serializationObject = _super.prototype.serialize.call(this);
  32072. serializationObject.width = this.width;
  32073. serializationObject.height = this.height;
  32074. serializationObject.subdivisions = this.subdivisions;
  32075. return serializationObject;
  32076. };
  32077. Ground.Parse = function (parsedGround, scene) {
  32078. if (scene.getGeometryByID(parsedGround.id)) {
  32079. return null; // null since geometry could be something else than a ground...
  32080. }
  32081. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  32082. if (BABYLON.Tags) {
  32083. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  32084. }
  32085. scene.pushGeometry(ground, true);
  32086. return ground;
  32087. };
  32088. return Ground;
  32089. }(_Primitive));
  32090. Primitives.Ground = Ground;
  32091. var TiledGround = /** @class */ (function (_super) {
  32092. __extends(TiledGround, _super);
  32093. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  32094. if (mesh === void 0) { mesh = null; }
  32095. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32096. _this.xmin = xmin;
  32097. _this.zmin = zmin;
  32098. _this.xmax = xmax;
  32099. _this.zmax = zmax;
  32100. _this.subdivisions = subdivisions;
  32101. _this.precision = precision;
  32102. return _this;
  32103. }
  32104. TiledGround.prototype._regenerateVertexData = function () {
  32105. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  32106. };
  32107. TiledGround.prototype.copy = function (id) {
  32108. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  32109. };
  32110. return TiledGround;
  32111. }(_Primitive));
  32112. Primitives.TiledGround = TiledGround;
  32113. var Plane = /** @class */ (function (_super) {
  32114. __extends(Plane, _super);
  32115. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  32116. if (mesh === void 0) { mesh = null; }
  32117. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32118. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32119. _this.size = size;
  32120. _this.side = side;
  32121. return _this;
  32122. }
  32123. Plane.prototype._regenerateVertexData = function () {
  32124. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  32125. };
  32126. Plane.prototype.copy = function (id) {
  32127. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32128. };
  32129. Plane.prototype.serialize = function () {
  32130. var serializationObject = _super.prototype.serialize.call(this);
  32131. serializationObject.size = this.size;
  32132. return serializationObject;
  32133. };
  32134. Plane.Parse = function (parsedPlane, scene) {
  32135. if (scene.getGeometryByID(parsedPlane.id)) {
  32136. return null; // null since geometry could be something else than a ground...
  32137. }
  32138. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  32139. if (BABYLON.Tags) {
  32140. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  32141. }
  32142. scene.pushGeometry(plane, true);
  32143. return plane;
  32144. };
  32145. return Plane;
  32146. }(_Primitive));
  32147. Primitives.Plane = Plane;
  32148. var TorusKnot = /** @class */ (function (_super) {
  32149. __extends(TorusKnot, _super);
  32150. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  32151. if (mesh === void 0) { mesh = null; }
  32152. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32153. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32154. _this.radius = radius;
  32155. _this.tube = tube;
  32156. _this.radialSegments = radialSegments;
  32157. _this.tubularSegments = tubularSegments;
  32158. _this.p = p;
  32159. _this.q = q;
  32160. _this.side = side;
  32161. return _this;
  32162. }
  32163. TorusKnot.prototype._regenerateVertexData = function () {
  32164. 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 });
  32165. };
  32166. TorusKnot.prototype.copy = function (id) {
  32167. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  32168. };
  32169. TorusKnot.prototype.serialize = function () {
  32170. var serializationObject = _super.prototype.serialize.call(this);
  32171. serializationObject.radius = this.radius;
  32172. serializationObject.tube = this.tube;
  32173. serializationObject.radialSegments = this.radialSegments;
  32174. serializationObject.tubularSegments = this.tubularSegments;
  32175. serializationObject.p = this.p;
  32176. serializationObject.q = this.q;
  32177. return serializationObject;
  32178. };
  32179. ;
  32180. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  32181. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  32182. return null; // null since geometry could be something else than a ground...
  32183. }
  32184. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  32185. if (BABYLON.Tags) {
  32186. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  32187. }
  32188. scene.pushGeometry(torusKnot, true);
  32189. return torusKnot;
  32190. };
  32191. return TorusKnot;
  32192. }(_Primitive));
  32193. Primitives.TorusKnot = TorusKnot;
  32194. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  32195. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  32196. })(BABYLON || (BABYLON = {}));
  32197. //# sourceMappingURL=babylon.geometry.js.map
  32198. var BABYLON;
  32199. (function (BABYLON) {
  32200. var PostProcessManager = /** @class */ (function () {
  32201. function PostProcessManager(scene) {
  32202. this._vertexBuffers = {};
  32203. this._scene = scene;
  32204. }
  32205. PostProcessManager.prototype._prepareBuffers = function () {
  32206. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  32207. return;
  32208. }
  32209. // VBO
  32210. var vertices = [];
  32211. vertices.push(1, 1);
  32212. vertices.push(-1, 1);
  32213. vertices.push(-1, -1);
  32214. vertices.push(1, -1);
  32215. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  32216. this._buildIndexBuffer();
  32217. };
  32218. PostProcessManager.prototype._buildIndexBuffer = function () {
  32219. // Indices
  32220. var indices = [];
  32221. indices.push(0);
  32222. indices.push(1);
  32223. indices.push(2);
  32224. indices.push(0);
  32225. indices.push(2);
  32226. indices.push(3);
  32227. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  32228. };
  32229. PostProcessManager.prototype._rebuild = function () {
  32230. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32231. if (!vb) {
  32232. return;
  32233. }
  32234. vb._rebuild();
  32235. this._buildIndexBuffer();
  32236. };
  32237. // Methods
  32238. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  32239. if (sourceTexture === void 0) { sourceTexture = null; }
  32240. if (postProcesses === void 0) { postProcesses = null; }
  32241. var camera = this._scene.activeCamera;
  32242. if (!camera) {
  32243. return false;
  32244. }
  32245. var postProcesses = postProcesses || camera._postProcesses;
  32246. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32247. return false;
  32248. }
  32249. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  32250. return true;
  32251. };
  32252. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  32253. if (targetTexture === void 0) { targetTexture = null; }
  32254. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32255. if (!this._scene.activeCamera) {
  32256. return;
  32257. }
  32258. var engine = this._scene.getEngine();
  32259. for (var index = 0; index < postProcesses.length; index++) {
  32260. if (index < postProcesses.length - 1) {
  32261. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  32262. }
  32263. else {
  32264. if (targetTexture) {
  32265. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  32266. }
  32267. else {
  32268. engine.restoreDefaultFramebuffer();
  32269. }
  32270. }
  32271. var pp = postProcesses[index];
  32272. var effect = pp.apply();
  32273. if (effect) {
  32274. pp.onBeforeRenderObservable.notifyObservers(effect);
  32275. // VBOs
  32276. this._prepareBuffers();
  32277. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32278. // Draw order
  32279. engine.draw(true, 0, 6);
  32280. pp.onAfterRenderObservable.notifyObservers(effect);
  32281. }
  32282. }
  32283. // Restore depth buffer
  32284. engine.setDepthBuffer(true);
  32285. engine.setDepthWrite(true);
  32286. };
  32287. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  32288. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32289. var camera = this._scene.activeCamera;
  32290. if (!camera) {
  32291. return;
  32292. }
  32293. postProcesses = postProcesses || camera._postProcesses;
  32294. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32295. return;
  32296. }
  32297. var engine = this._scene.getEngine();
  32298. for (var index = 0, len = postProcesses.length; index < len; index++) {
  32299. if (index < len - 1) {
  32300. postProcesses[index + 1].activate(camera, targetTexture);
  32301. }
  32302. else {
  32303. if (targetTexture) {
  32304. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  32305. }
  32306. else {
  32307. engine.restoreDefaultFramebuffer();
  32308. }
  32309. }
  32310. if (doNotPresent) {
  32311. break;
  32312. }
  32313. var pp = postProcesses[index];
  32314. var effect = pp.apply();
  32315. if (effect) {
  32316. pp.onBeforeRenderObservable.notifyObservers(effect);
  32317. // VBOs
  32318. this._prepareBuffers();
  32319. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32320. // Draw order
  32321. engine.draw(true, 0, 6);
  32322. pp.onAfterRenderObservable.notifyObservers(effect);
  32323. }
  32324. }
  32325. // Restore states
  32326. engine.setDepthBuffer(true);
  32327. engine.setDepthWrite(true);
  32328. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32329. };
  32330. PostProcessManager.prototype.dispose = function () {
  32331. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32332. if (buffer) {
  32333. buffer.dispose();
  32334. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32335. }
  32336. if (this._indexBuffer) {
  32337. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32338. this._indexBuffer = null;
  32339. }
  32340. };
  32341. return PostProcessManager;
  32342. }());
  32343. BABYLON.PostProcessManager = PostProcessManager;
  32344. })(BABYLON || (BABYLON = {}));
  32345. //# sourceMappingURL=babylon.postProcessManager.js.map
  32346. var BABYLON;
  32347. (function (BABYLON) {
  32348. /**
  32349. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  32350. */
  32351. var PerformanceMonitor = /** @class */ (function () {
  32352. /**
  32353. * constructor
  32354. * @param frameSampleSize The number of samples required to saturate the sliding window
  32355. */
  32356. function PerformanceMonitor(frameSampleSize) {
  32357. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  32358. this._enabled = true;
  32359. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  32360. }
  32361. /**
  32362. * Samples current frame
  32363. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  32364. */
  32365. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  32366. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  32367. if (!this._enabled)
  32368. return;
  32369. if (this._lastFrameTimeMs != null) {
  32370. var dt = timeMs - this._lastFrameTimeMs;
  32371. this._rollingFrameTime.add(dt);
  32372. }
  32373. this._lastFrameTimeMs = timeMs;
  32374. };
  32375. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  32376. /**
  32377. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32378. * @return Average frame time in milliseconds
  32379. */
  32380. get: function () {
  32381. return this._rollingFrameTime.average;
  32382. },
  32383. enumerable: true,
  32384. configurable: true
  32385. });
  32386. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  32387. /**
  32388. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32389. * @return Frame time variance in milliseconds squared
  32390. */
  32391. get: function () {
  32392. return this._rollingFrameTime.variance;
  32393. },
  32394. enumerable: true,
  32395. configurable: true
  32396. });
  32397. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  32398. /**
  32399. * Returns the frame time of the most recent frame
  32400. * @return Frame time in milliseconds
  32401. */
  32402. get: function () {
  32403. return this._rollingFrameTime.history(0);
  32404. },
  32405. enumerable: true,
  32406. configurable: true
  32407. });
  32408. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  32409. /**
  32410. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  32411. * @return Framerate in frames per second
  32412. */
  32413. get: function () {
  32414. return 1000.0 / this._rollingFrameTime.average;
  32415. },
  32416. enumerable: true,
  32417. configurable: true
  32418. });
  32419. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  32420. /**
  32421. * Returns the average framerate in frames per second using the most recent frame time
  32422. * @return Framerate in frames per second
  32423. */
  32424. get: function () {
  32425. var history = this._rollingFrameTime.history(0);
  32426. if (history === 0) {
  32427. return 0;
  32428. }
  32429. return 1000.0 / history;
  32430. },
  32431. enumerable: true,
  32432. configurable: true
  32433. });
  32434. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  32435. /**
  32436. * Returns true if enough samples have been taken to completely fill the sliding window
  32437. * @return true if saturated
  32438. */
  32439. get: function () {
  32440. return this._rollingFrameTime.isSaturated();
  32441. },
  32442. enumerable: true,
  32443. configurable: true
  32444. });
  32445. /**
  32446. * Enables contributions to the sliding window sample set
  32447. */
  32448. PerformanceMonitor.prototype.enable = function () {
  32449. this._enabled = true;
  32450. };
  32451. /**
  32452. * Disables contributions to the sliding window sample set
  32453. * Samples will not be interpolated over the disabled period
  32454. */
  32455. PerformanceMonitor.prototype.disable = function () {
  32456. this._enabled = false;
  32457. //clear last sample to avoid interpolating over the disabled period when next enabled
  32458. this._lastFrameTimeMs = null;
  32459. };
  32460. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  32461. /**
  32462. * Returns true if sampling is enabled
  32463. * @return true if enabled
  32464. */
  32465. get: function () {
  32466. return this._enabled;
  32467. },
  32468. enumerable: true,
  32469. configurable: true
  32470. });
  32471. /**
  32472. * Resets performance monitor
  32473. */
  32474. PerformanceMonitor.prototype.reset = function () {
  32475. //clear last sample to avoid interpolating over the disabled period when next enabled
  32476. this._lastFrameTimeMs = null;
  32477. //wipe record
  32478. this._rollingFrameTime.reset();
  32479. };
  32480. return PerformanceMonitor;
  32481. }());
  32482. BABYLON.PerformanceMonitor = PerformanceMonitor;
  32483. /**
  32484. * RollingAverage
  32485. *
  32486. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  32487. */
  32488. var RollingAverage = /** @class */ (function () {
  32489. /**
  32490. * constructor
  32491. * @param length The number of samples required to saturate the sliding window
  32492. */
  32493. function RollingAverage(length) {
  32494. this._samples = new Array(length);
  32495. this.reset();
  32496. }
  32497. /**
  32498. * Adds a sample to the sample set
  32499. * @param v The sample value
  32500. */
  32501. RollingAverage.prototype.add = function (v) {
  32502. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  32503. var delta;
  32504. //we need to check if we've already wrapped round
  32505. if (this.isSaturated()) {
  32506. //remove bottom of stack from mean
  32507. var bottomValue = this._samples[this._pos];
  32508. delta = bottomValue - this.average;
  32509. this.average -= delta / (this._sampleCount - 1);
  32510. this._m2 -= delta * (bottomValue - this.average);
  32511. }
  32512. else {
  32513. this._sampleCount++;
  32514. }
  32515. //add new value to mean
  32516. delta = v - this.average;
  32517. this.average += delta / (this._sampleCount);
  32518. this._m2 += delta * (v - this.average);
  32519. //set the new variance
  32520. this.variance = this._m2 / (this._sampleCount - 1);
  32521. this._samples[this._pos] = v;
  32522. this._pos++;
  32523. this._pos %= this._samples.length; //positive wrap around
  32524. };
  32525. /**
  32526. * Returns previously added values or null if outside of history or outside the sliding window domain
  32527. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  32528. * @return Value previously recorded with add() or null if outside of range
  32529. */
  32530. RollingAverage.prototype.history = function (i) {
  32531. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  32532. return 0;
  32533. }
  32534. var i0 = this._wrapPosition(this._pos - 1.0);
  32535. return this._samples[this._wrapPosition(i0 - i)];
  32536. };
  32537. /**
  32538. * Returns true if enough samples have been taken to completely fill the sliding window
  32539. * @return true if sample-set saturated
  32540. */
  32541. RollingAverage.prototype.isSaturated = function () {
  32542. return this._sampleCount >= this._samples.length;
  32543. };
  32544. /**
  32545. * Resets the rolling average (equivalent to 0 samples taken so far)
  32546. */
  32547. RollingAverage.prototype.reset = function () {
  32548. this.average = 0;
  32549. this.variance = 0;
  32550. this._sampleCount = 0;
  32551. this._pos = 0;
  32552. this._m2 = 0;
  32553. };
  32554. /**
  32555. * Wraps a value around the sample range boundaries
  32556. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  32557. * @return Wrapped position in sample range
  32558. */
  32559. RollingAverage.prototype._wrapPosition = function (i) {
  32560. var max = this._samples.length;
  32561. return ((i % max) + max) % max;
  32562. };
  32563. return RollingAverage;
  32564. }());
  32565. BABYLON.RollingAverage = RollingAverage;
  32566. })(BABYLON || (BABYLON = {}));
  32567. //# sourceMappingURL=babylon.performanceMonitor.js.map
  32568. var BABYLON;
  32569. (function (BABYLON) {
  32570. /**
  32571. * This groups together the common properties used for image processing either in direct forward pass
  32572. * or through post processing effect depending on the use of the image processing pipeline in your scene
  32573. * or not.
  32574. */
  32575. var ImageProcessingConfiguration = /** @class */ (function () {
  32576. function ImageProcessingConfiguration() {
  32577. /**
  32578. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  32579. */
  32580. this.colorCurves = new BABYLON.ColorCurves();
  32581. this._colorCurvesEnabled = false;
  32582. this._colorGradingEnabled = false;
  32583. this._colorGradingWithGreenDepth = true;
  32584. this._colorGradingBGR = true;
  32585. this._exposure = 1.0;
  32586. this._toneMappingEnabled = false;
  32587. this._contrast = 1.0;
  32588. /**
  32589. * Vignette stretch size.
  32590. */
  32591. this.vignetteStretch = 0;
  32592. /**
  32593. * Vignette centre X Offset.
  32594. */
  32595. this.vignetteCentreX = 0;
  32596. /**
  32597. * Vignette centre Y Offset.
  32598. */
  32599. this.vignetteCentreY = 0;
  32600. /**
  32601. * Vignette weight or intensity of the vignette effect.
  32602. */
  32603. this.vignetteWeight = 1.5;
  32604. /**
  32605. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  32606. * if vignetteEnabled is set to true.
  32607. */
  32608. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  32609. /**
  32610. * Camera field of view used by the Vignette effect.
  32611. */
  32612. this.vignetteCameraFov = 0.5;
  32613. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  32614. this._vignetteEnabled = false;
  32615. this._applyByPostProcess = false;
  32616. this._isEnabled = true;
  32617. /**
  32618. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  32619. * @type {BABYLON.Observable}
  32620. */
  32621. this.onUpdateParameters = new BABYLON.Observable();
  32622. }
  32623. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  32624. /**
  32625. * Gets wether the color curves effect is enabled.
  32626. */
  32627. get: function () {
  32628. return this._colorCurvesEnabled;
  32629. },
  32630. /**
  32631. * Sets wether the color curves effect is enabled.
  32632. */
  32633. set: function (value) {
  32634. if (this._colorCurvesEnabled === value) {
  32635. return;
  32636. }
  32637. this._colorCurvesEnabled = value;
  32638. this._updateParameters();
  32639. },
  32640. enumerable: true,
  32641. configurable: true
  32642. });
  32643. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  32644. /**
  32645. * Gets wether the color grading effect is enabled.
  32646. */
  32647. get: function () {
  32648. return this._colorGradingEnabled;
  32649. },
  32650. /**
  32651. * Sets wether the color grading effect is enabled.
  32652. */
  32653. set: function (value) {
  32654. if (this._colorGradingEnabled === value) {
  32655. return;
  32656. }
  32657. this._colorGradingEnabled = value;
  32658. this._updateParameters();
  32659. },
  32660. enumerable: true,
  32661. configurable: true
  32662. });
  32663. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  32664. /**
  32665. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  32666. */
  32667. get: function () {
  32668. return this._colorGradingWithGreenDepth;
  32669. },
  32670. /**
  32671. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  32672. */
  32673. set: function (value) {
  32674. if (this._colorGradingWithGreenDepth === value) {
  32675. return;
  32676. }
  32677. this._colorGradingWithGreenDepth = value;
  32678. this._updateParameters();
  32679. },
  32680. enumerable: true,
  32681. configurable: true
  32682. });
  32683. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  32684. /**
  32685. * Gets wether the color grading texture contains BGR values.
  32686. */
  32687. get: function () {
  32688. return this._colorGradingBGR;
  32689. },
  32690. /**
  32691. * Sets wether the color grading texture contains BGR values.
  32692. */
  32693. set: function (value) {
  32694. if (this._colorGradingBGR === value) {
  32695. return;
  32696. }
  32697. this._colorGradingBGR = value;
  32698. this._updateParameters();
  32699. },
  32700. enumerable: true,
  32701. configurable: true
  32702. });
  32703. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  32704. /**
  32705. * Gets the Exposure used in the effect.
  32706. */
  32707. get: function () {
  32708. return this._exposure;
  32709. },
  32710. /**
  32711. * Sets the Exposure used in the effect.
  32712. */
  32713. set: function (value) {
  32714. if (this._exposure === value) {
  32715. return;
  32716. }
  32717. this._exposure = value;
  32718. this._updateParameters();
  32719. },
  32720. enumerable: true,
  32721. configurable: true
  32722. });
  32723. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  32724. /**
  32725. * Gets wether the tone mapping effect is enabled.
  32726. */
  32727. get: function () {
  32728. return this._toneMappingEnabled;
  32729. },
  32730. /**
  32731. * Sets wether the tone mapping effect is enabled.
  32732. */
  32733. set: function (value) {
  32734. if (this._toneMappingEnabled === value) {
  32735. return;
  32736. }
  32737. this._toneMappingEnabled = value;
  32738. this._updateParameters();
  32739. },
  32740. enumerable: true,
  32741. configurable: true
  32742. });
  32743. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  32744. /**
  32745. * Gets the contrast used in the effect.
  32746. */
  32747. get: function () {
  32748. return this._contrast;
  32749. },
  32750. /**
  32751. * Sets the contrast used in the effect.
  32752. */
  32753. set: function (value) {
  32754. if (this._contrast === value) {
  32755. return;
  32756. }
  32757. this._contrast = value;
  32758. this._updateParameters();
  32759. },
  32760. enumerable: true,
  32761. configurable: true
  32762. });
  32763. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  32764. /**
  32765. * Gets the vignette blend mode allowing different kind of effect.
  32766. */
  32767. get: function () {
  32768. return this._vignetteBlendMode;
  32769. },
  32770. /**
  32771. * Sets the vignette blend mode allowing different kind of effect.
  32772. */
  32773. set: function (value) {
  32774. if (this._vignetteBlendMode === value) {
  32775. return;
  32776. }
  32777. this._vignetteBlendMode = value;
  32778. this._updateParameters();
  32779. },
  32780. enumerable: true,
  32781. configurable: true
  32782. });
  32783. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  32784. /**
  32785. * Gets wether the vignette effect is enabled.
  32786. */
  32787. get: function () {
  32788. return this._vignetteEnabled;
  32789. },
  32790. /**
  32791. * Sets wether the vignette effect is enabled.
  32792. */
  32793. set: function (value) {
  32794. if (this._vignetteEnabled === value) {
  32795. return;
  32796. }
  32797. this._vignetteEnabled = value;
  32798. this._updateParameters();
  32799. },
  32800. enumerable: true,
  32801. configurable: true
  32802. });
  32803. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  32804. /**
  32805. * Gets wether the image processing is applied through a post process or not.
  32806. */
  32807. get: function () {
  32808. return this._applyByPostProcess;
  32809. },
  32810. /**
  32811. * Sets wether the image processing is applied through a post process or not.
  32812. */
  32813. set: function (value) {
  32814. if (this._applyByPostProcess === value) {
  32815. return;
  32816. }
  32817. this._applyByPostProcess = value;
  32818. this._updateParameters();
  32819. },
  32820. enumerable: true,
  32821. configurable: true
  32822. });
  32823. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  32824. /**
  32825. * Gets wether the image processing is enabled or not.
  32826. */
  32827. get: function () {
  32828. return this._isEnabled;
  32829. },
  32830. /**
  32831. * Sets wether the image processing is enabled or not.
  32832. */
  32833. set: function (value) {
  32834. if (this._isEnabled === value) {
  32835. return;
  32836. }
  32837. this._isEnabled = value;
  32838. this._updateParameters();
  32839. },
  32840. enumerable: true,
  32841. configurable: true
  32842. });
  32843. /**
  32844. * Method called each time the image processing information changes requires to recompile the effect.
  32845. */
  32846. ImageProcessingConfiguration.prototype._updateParameters = function () {
  32847. this.onUpdateParameters.notifyObservers(this);
  32848. };
  32849. ImageProcessingConfiguration.prototype.getClassName = function () {
  32850. return "ImageProcessingConfiguration";
  32851. };
  32852. /**
  32853. * Prepare the list of uniforms associated with the Image Processing effects.
  32854. * @param uniformsList The list of uniforms used in the effect
  32855. * @param defines the list of defines currently in use
  32856. */
  32857. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  32858. if (defines.EXPOSURE) {
  32859. uniforms.push("exposureLinear");
  32860. }
  32861. if (defines.CONTRAST) {
  32862. uniforms.push("contrast");
  32863. }
  32864. if (defines.COLORGRADING) {
  32865. uniforms.push("colorTransformSettings");
  32866. }
  32867. if (defines.VIGNETTE) {
  32868. uniforms.push("vInverseScreenSize");
  32869. uniforms.push("vignetteSettings1");
  32870. uniforms.push("vignetteSettings2");
  32871. }
  32872. if (defines.COLORCURVES) {
  32873. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  32874. }
  32875. };
  32876. /**
  32877. * Prepare the list of samplers associated with the Image Processing effects.
  32878. * @param uniformsList The list of uniforms used in the effect
  32879. * @param defines the list of defines currently in use
  32880. */
  32881. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  32882. if (defines.COLORGRADING) {
  32883. samplersList.push("txColorTransform");
  32884. }
  32885. };
  32886. /**
  32887. * Prepare the list of defines associated to the shader.
  32888. * @param defines the list of defines to complete
  32889. */
  32890. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  32891. if (forPostProcess === void 0) { forPostProcess = false; }
  32892. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  32893. defines.VIGNETTE = false;
  32894. defines.TONEMAPPING = false;
  32895. defines.CONTRAST = false;
  32896. defines.EXPOSURE = false;
  32897. defines.COLORCURVES = false;
  32898. defines.COLORGRADING = false;
  32899. defines.COLORGRADING3D = false;
  32900. defines.IMAGEPROCESSING = false;
  32901. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  32902. return;
  32903. }
  32904. defines.VIGNETTE = this.vignetteEnabled;
  32905. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  32906. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  32907. defines.TONEMAPPING = this.toneMappingEnabled;
  32908. defines.CONTRAST = (this.contrast !== 1.0);
  32909. defines.EXPOSURE = (this.exposure !== 1.0);
  32910. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  32911. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  32912. if (defines.COLORGRADING) {
  32913. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  32914. }
  32915. else {
  32916. defines.COLORGRADING3D = false;
  32917. }
  32918. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  32919. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  32920. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  32921. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  32922. };
  32923. /**
  32924. * Returns true if all the image processing information are ready.
  32925. */
  32926. ImageProcessingConfiguration.prototype.isReady = function () {
  32927. // Color Grading texure can not be none blocking.
  32928. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  32929. };
  32930. /**
  32931. * Binds the image processing to the shader.
  32932. * @param effect The effect to bind to
  32933. */
  32934. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  32935. if (aspectRatio === void 0) { aspectRatio = 1; }
  32936. // Color Curves
  32937. if (this._colorCurvesEnabled && this.colorCurves) {
  32938. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  32939. }
  32940. // Vignette
  32941. if (this._vignetteEnabled) {
  32942. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  32943. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  32944. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  32945. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  32946. var vignetteScaleX = vignetteScaleY * aspectRatio;
  32947. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  32948. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  32949. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  32950. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  32951. var vignettePower = -2.0 * this.vignetteWeight;
  32952. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  32953. }
  32954. // Exposure
  32955. effect.setFloat("exposureLinear", this.exposure);
  32956. // Contrast
  32957. effect.setFloat("contrast", this.contrast);
  32958. // Color transform settings
  32959. if (this.colorGradingTexture) {
  32960. effect.setTexture("txColorTransform", this.colorGradingTexture);
  32961. var textureSize = this.colorGradingTexture.getSize().height;
  32962. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  32963. 0.5 / textureSize, // textureOffset
  32964. textureSize, // textureSize
  32965. this.colorGradingTexture.level // weight
  32966. );
  32967. }
  32968. };
  32969. /**
  32970. * Clones the current image processing instance.
  32971. * @return The cloned image processing
  32972. */
  32973. ImageProcessingConfiguration.prototype.clone = function () {
  32974. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  32975. };
  32976. /**
  32977. * Serializes the current image processing instance to a json representation.
  32978. * @return a JSON representation
  32979. */
  32980. ImageProcessingConfiguration.prototype.serialize = function () {
  32981. return BABYLON.SerializationHelper.Serialize(this);
  32982. };
  32983. /**
  32984. * Parses the image processing from a json representation.
  32985. * @param source the JSON source to parse
  32986. * @return The parsed image processing
  32987. */
  32988. ImageProcessingConfiguration.Parse = function (source) {
  32989. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  32990. };
  32991. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  32992. /**
  32993. * Used to apply the vignette as a mix with the pixel color.
  32994. */
  32995. get: function () {
  32996. return this._VIGNETTEMODE_MULTIPLY;
  32997. },
  32998. enumerable: true,
  32999. configurable: true
  33000. });
  33001. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  33002. /**
  33003. * Used to apply the vignette as a replacement of the pixel color.
  33004. */
  33005. get: function () {
  33006. return this._VIGNETTEMODE_OPAQUE;
  33007. },
  33008. enumerable: true,
  33009. configurable: true
  33010. });
  33011. // Static constants associated to the image processing.
  33012. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  33013. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  33014. __decorate([
  33015. BABYLON.serializeAsColorCurves()
  33016. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  33017. __decorate([
  33018. BABYLON.serialize()
  33019. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  33020. __decorate([
  33021. BABYLON.serializeAsTexture()
  33022. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  33023. __decorate([
  33024. BABYLON.serialize()
  33025. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  33026. __decorate([
  33027. BABYLON.serialize()
  33028. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  33029. __decorate([
  33030. BABYLON.serialize()
  33031. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  33032. __decorate([
  33033. BABYLON.serialize()
  33034. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  33035. __decorate([
  33036. BABYLON.serialize()
  33037. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  33038. __decorate([
  33039. BABYLON.serialize()
  33040. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  33041. __decorate([
  33042. BABYLON.serialize()
  33043. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  33044. __decorate([
  33045. BABYLON.serialize()
  33046. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  33047. __decorate([
  33048. BABYLON.serialize()
  33049. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  33050. __decorate([
  33051. BABYLON.serialize()
  33052. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  33053. __decorate([
  33054. BABYLON.serializeAsColor4()
  33055. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  33056. __decorate([
  33057. BABYLON.serialize()
  33058. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  33059. __decorate([
  33060. BABYLON.serialize()
  33061. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  33062. __decorate([
  33063. BABYLON.serialize()
  33064. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  33065. __decorate([
  33066. BABYLON.serialize()
  33067. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  33068. __decorate([
  33069. BABYLON.serialize()
  33070. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  33071. return ImageProcessingConfiguration;
  33072. }());
  33073. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  33074. })(BABYLON || (BABYLON = {}));
  33075. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  33076. var BABYLON;
  33077. (function (BABYLON) {
  33078. /**
  33079. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  33080. * It can help converting any input color in a desired output one. This can then be used to create effects
  33081. * from sepia, black and white to sixties or futuristic rendering...
  33082. *
  33083. * The only supported format is currently 3dl.
  33084. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  33085. */
  33086. var ColorGradingTexture = /** @class */ (function (_super) {
  33087. __extends(ColorGradingTexture, _super);
  33088. /**
  33089. * Instantiates a ColorGradingTexture from the following parameters.
  33090. *
  33091. * @param url The location of the color gradind data (currently only supporting 3dl)
  33092. * @param scene The scene the texture will be used in
  33093. */
  33094. function ColorGradingTexture(url, scene) {
  33095. var _this = _super.call(this, scene) || this;
  33096. if (!url) {
  33097. return _this;
  33098. }
  33099. _this._engine = scene.getEngine();
  33100. _this._textureMatrix = BABYLON.Matrix.Identity();
  33101. _this.name = url;
  33102. _this.url = url;
  33103. _this.hasAlpha = false;
  33104. _this.isCube = false;
  33105. _this.is3D = _this._engine.webGLVersion > 1;
  33106. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33107. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33108. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33109. _this.anisotropicFilteringLevel = 1;
  33110. _this._texture = _this._getFromCache(url, true);
  33111. if (!_this._texture) {
  33112. if (!scene.useDelayedTextureLoading) {
  33113. _this.loadTexture();
  33114. }
  33115. else {
  33116. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33117. }
  33118. }
  33119. return _this;
  33120. }
  33121. /**
  33122. * Returns the texture matrix used in most of the material.
  33123. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  33124. */
  33125. ColorGradingTexture.prototype.getTextureMatrix = function () {
  33126. return this._textureMatrix;
  33127. };
  33128. /**
  33129. * Occurs when the file being loaded is a .3dl LUT file.
  33130. */
  33131. ColorGradingTexture.prototype.load3dlTexture = function () {
  33132. var engine = this._engine;
  33133. var texture;
  33134. if (engine.webGLVersion === 1) {
  33135. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33136. }
  33137. else {
  33138. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33139. }
  33140. this._texture = texture;
  33141. var callback = function (text) {
  33142. var data = null;
  33143. var tempData = null;
  33144. var line;
  33145. var lines = text.split('\n');
  33146. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  33147. var maxColor = 0;
  33148. for (var i = 0; i < lines.length; i++) {
  33149. line = lines[i];
  33150. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  33151. continue;
  33152. if (line.indexOf('#') === 0)
  33153. continue;
  33154. var words = line.split(" ");
  33155. if (size === 0) {
  33156. // Number of space + one
  33157. size = words.length;
  33158. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  33159. tempData = new Float32Array(size * size * size * 4);
  33160. continue;
  33161. }
  33162. if (size != 0) {
  33163. var r = Math.max(parseInt(words[0]), 0);
  33164. var g = Math.max(parseInt(words[1]), 0);
  33165. var b = Math.max(parseInt(words[2]), 0);
  33166. maxColor = Math.max(r, maxColor);
  33167. maxColor = Math.max(g, maxColor);
  33168. maxColor = Math.max(b, maxColor);
  33169. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  33170. if (tempData) {
  33171. tempData[pixelStorageIndex + 0] = r;
  33172. tempData[pixelStorageIndex + 1] = g;
  33173. tempData[pixelStorageIndex + 2] = b;
  33174. }
  33175. pixelIndexSlice++;
  33176. if (pixelIndexSlice % size == 0) {
  33177. pixelIndexH++;
  33178. pixelIndexSlice = 0;
  33179. if (pixelIndexH % size == 0) {
  33180. pixelIndexW++;
  33181. pixelIndexH = 0;
  33182. }
  33183. }
  33184. }
  33185. }
  33186. if (tempData && data) {
  33187. for (var i = 0; i < tempData.length; i++) {
  33188. if (i > 0 && (i + 1) % 4 === 0) {
  33189. data[i] = 255;
  33190. }
  33191. else {
  33192. var value = tempData[i];
  33193. data[i] = (value / maxColor * 255);
  33194. }
  33195. }
  33196. }
  33197. if (texture.is3D) {
  33198. texture.updateSize(size, size, size);
  33199. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33200. }
  33201. else {
  33202. texture.updateSize(size * size, size);
  33203. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33204. }
  33205. };
  33206. BABYLON.Tools.LoadFile(this.url, callback);
  33207. return this._texture;
  33208. };
  33209. /**
  33210. * Starts the loading process of the texture.
  33211. */
  33212. ColorGradingTexture.prototype.loadTexture = function () {
  33213. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  33214. this.load3dlTexture();
  33215. }
  33216. };
  33217. /**
  33218. * Clones the color gradind texture.
  33219. */
  33220. ColorGradingTexture.prototype.clone = function () {
  33221. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  33222. // Base texture
  33223. newTexture.level = this.level;
  33224. return newTexture;
  33225. };
  33226. /**
  33227. * Called during delayed load for textures.
  33228. */
  33229. ColorGradingTexture.prototype.delayLoad = function () {
  33230. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33231. return;
  33232. }
  33233. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33234. this._texture = this._getFromCache(this.url, true);
  33235. if (!this._texture) {
  33236. this.loadTexture();
  33237. }
  33238. };
  33239. /**
  33240. * Parses a color grading texture serialized by Babylon.
  33241. * @param parsedTexture The texture information being parsedTexture
  33242. * @param scene The scene to load the texture in
  33243. * @param rootUrl The root url of the data assets to load
  33244. * @return A color gradind texture
  33245. */
  33246. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  33247. var texture = null;
  33248. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  33249. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  33250. texture.name = parsedTexture.name;
  33251. texture.level = parsedTexture.level;
  33252. }
  33253. return texture;
  33254. };
  33255. /**
  33256. * Serializes the LUT texture to json format.
  33257. */
  33258. ColorGradingTexture.prototype.serialize = function () {
  33259. if (!this.name) {
  33260. return null;
  33261. }
  33262. var serializationObject = {};
  33263. serializationObject.name = this.name;
  33264. serializationObject.level = this.level;
  33265. serializationObject.customType = "BABYLON.ColorGradingTexture";
  33266. return serializationObject;
  33267. };
  33268. /**
  33269. * Empty line regex stored for GC.
  33270. */
  33271. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  33272. return ColorGradingTexture;
  33273. }(BABYLON.BaseTexture));
  33274. BABYLON.ColorGradingTexture = ColorGradingTexture;
  33275. })(BABYLON || (BABYLON = {}));
  33276. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  33277. var BABYLON;
  33278. (function (BABYLON) {
  33279. /**
  33280. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33281. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33282. * 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;
  33283. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33284. */
  33285. var ColorCurves = /** @class */ (function () {
  33286. function ColorCurves() {
  33287. this._dirty = true;
  33288. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  33289. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  33290. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33291. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  33292. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33293. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  33294. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  33295. this._globalHue = 30;
  33296. this._globalDensity = 0;
  33297. this._globalSaturation = 0;
  33298. this._globalExposure = 0;
  33299. this._highlightsHue = 30;
  33300. this._highlightsDensity = 0;
  33301. this._highlightsSaturation = 0;
  33302. this._highlightsExposure = 0;
  33303. this._midtonesHue = 30;
  33304. this._midtonesDensity = 0;
  33305. this._midtonesSaturation = 0;
  33306. this._midtonesExposure = 0;
  33307. this._shadowsHue = 30;
  33308. this._shadowsDensity = 0;
  33309. this._shadowsSaturation = 0;
  33310. this._shadowsExposure = 0;
  33311. }
  33312. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  33313. /**
  33314. * Gets the global Hue value.
  33315. * 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).
  33316. */
  33317. get: function () {
  33318. return this._globalHue;
  33319. },
  33320. /**
  33321. * Sets the global Hue value.
  33322. * 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).
  33323. */
  33324. set: function (value) {
  33325. this._globalHue = value;
  33326. this._dirty = true;
  33327. },
  33328. enumerable: true,
  33329. configurable: true
  33330. });
  33331. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  33332. /**
  33333. * Gets the global Density value.
  33334. * 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.
  33335. * Values less than zero provide a filter of opposite hue.
  33336. */
  33337. get: function () {
  33338. return this._globalDensity;
  33339. },
  33340. /**
  33341. * Sets the global Density value.
  33342. * 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.
  33343. * Values less than zero provide a filter of opposite hue.
  33344. */
  33345. set: function (value) {
  33346. this._globalDensity = value;
  33347. this._dirty = true;
  33348. },
  33349. enumerable: true,
  33350. configurable: true
  33351. });
  33352. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  33353. /**
  33354. * Gets the global Saturation value.
  33355. * 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.
  33356. */
  33357. get: function () {
  33358. return this._globalSaturation;
  33359. },
  33360. /**
  33361. * Sets the global Saturation value.
  33362. * 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.
  33363. */
  33364. set: function (value) {
  33365. this._globalSaturation = value;
  33366. this._dirty = true;
  33367. },
  33368. enumerable: true,
  33369. configurable: true
  33370. });
  33371. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  33372. /**
  33373. * Gets the highlights Hue value.
  33374. * 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).
  33375. */
  33376. get: function () {
  33377. return this._highlightsHue;
  33378. },
  33379. /**
  33380. * Sets the highlights Hue value.
  33381. * 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).
  33382. */
  33383. set: function (value) {
  33384. this._highlightsHue = value;
  33385. this._dirty = true;
  33386. },
  33387. enumerable: true,
  33388. configurable: true
  33389. });
  33390. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  33391. /**
  33392. * Gets the highlights Density value.
  33393. * 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.
  33394. * Values less than zero provide a filter of opposite hue.
  33395. */
  33396. get: function () {
  33397. return this._highlightsDensity;
  33398. },
  33399. /**
  33400. * Sets the highlights Density value.
  33401. * 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.
  33402. * Values less than zero provide a filter of opposite hue.
  33403. */
  33404. set: function (value) {
  33405. this._highlightsDensity = value;
  33406. this._dirty = true;
  33407. },
  33408. enumerable: true,
  33409. configurable: true
  33410. });
  33411. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  33412. /**
  33413. * Gets the highlights Saturation value.
  33414. * 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.
  33415. */
  33416. get: function () {
  33417. return this._highlightsSaturation;
  33418. },
  33419. /**
  33420. * Sets the highlights Saturation value.
  33421. * 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.
  33422. */
  33423. set: function (value) {
  33424. this._highlightsSaturation = value;
  33425. this._dirty = true;
  33426. },
  33427. enumerable: true,
  33428. configurable: true
  33429. });
  33430. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  33431. /**
  33432. * Gets the highlights Exposure value.
  33433. * 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.
  33434. */
  33435. get: function () {
  33436. return this._highlightsExposure;
  33437. },
  33438. /**
  33439. * Sets the highlights Exposure value.
  33440. * 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.
  33441. */
  33442. set: function (value) {
  33443. this._highlightsExposure = value;
  33444. this._dirty = true;
  33445. },
  33446. enumerable: true,
  33447. configurable: true
  33448. });
  33449. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  33450. /**
  33451. * Gets the midtones Hue value.
  33452. * 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).
  33453. */
  33454. get: function () {
  33455. return this._midtonesHue;
  33456. },
  33457. /**
  33458. * Sets the midtones Hue value.
  33459. * 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).
  33460. */
  33461. set: function (value) {
  33462. this._midtonesHue = value;
  33463. this._dirty = true;
  33464. },
  33465. enumerable: true,
  33466. configurable: true
  33467. });
  33468. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  33469. /**
  33470. * Gets the midtones Density value.
  33471. * 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.
  33472. * Values less than zero provide a filter of opposite hue.
  33473. */
  33474. get: function () {
  33475. return this._midtonesDensity;
  33476. },
  33477. /**
  33478. * Sets the midtones Density value.
  33479. * 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.
  33480. * Values less than zero provide a filter of opposite hue.
  33481. */
  33482. set: function (value) {
  33483. this._midtonesDensity = value;
  33484. this._dirty = true;
  33485. },
  33486. enumerable: true,
  33487. configurable: true
  33488. });
  33489. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  33490. /**
  33491. * Gets the midtones Saturation value.
  33492. * 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.
  33493. */
  33494. get: function () {
  33495. return this._midtonesSaturation;
  33496. },
  33497. /**
  33498. * Sets the midtones Saturation value.
  33499. * 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.
  33500. */
  33501. set: function (value) {
  33502. this._midtonesSaturation = value;
  33503. this._dirty = true;
  33504. },
  33505. enumerable: true,
  33506. configurable: true
  33507. });
  33508. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  33509. /**
  33510. * Gets the midtones Exposure value.
  33511. * 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.
  33512. */
  33513. get: function () {
  33514. return this._midtonesExposure;
  33515. },
  33516. /**
  33517. * Sets the midtones Exposure value.
  33518. * 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.
  33519. */
  33520. set: function (value) {
  33521. this._midtonesExposure = value;
  33522. this._dirty = true;
  33523. },
  33524. enumerable: true,
  33525. configurable: true
  33526. });
  33527. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  33528. /**
  33529. * Gets the shadows Hue value.
  33530. * 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).
  33531. */
  33532. get: function () {
  33533. return this._shadowsHue;
  33534. },
  33535. /**
  33536. * Sets the shadows Hue value.
  33537. * 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).
  33538. */
  33539. set: function (value) {
  33540. this._shadowsHue = value;
  33541. this._dirty = true;
  33542. },
  33543. enumerable: true,
  33544. configurable: true
  33545. });
  33546. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  33547. /**
  33548. * Gets the shadows Density value.
  33549. * 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.
  33550. * Values less than zero provide a filter of opposite hue.
  33551. */
  33552. get: function () {
  33553. return this._shadowsDensity;
  33554. },
  33555. /**
  33556. * Sets the shadows Density value.
  33557. * 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.
  33558. * Values less than zero provide a filter of opposite hue.
  33559. */
  33560. set: function (value) {
  33561. this._shadowsDensity = value;
  33562. this._dirty = true;
  33563. },
  33564. enumerable: true,
  33565. configurable: true
  33566. });
  33567. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  33568. /**
  33569. * Gets the shadows Saturation value.
  33570. * 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.
  33571. */
  33572. get: function () {
  33573. return this._shadowsSaturation;
  33574. },
  33575. /**
  33576. * Sets the shadows Saturation value.
  33577. * 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.
  33578. */
  33579. set: function (value) {
  33580. this._shadowsSaturation = value;
  33581. this._dirty = true;
  33582. },
  33583. enumerable: true,
  33584. configurable: true
  33585. });
  33586. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  33587. /**
  33588. * Gets the shadows Exposure value.
  33589. * 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.
  33590. */
  33591. get: function () {
  33592. return this._shadowsExposure;
  33593. },
  33594. /**
  33595. * Sets the shadows Exposure value.
  33596. * 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.
  33597. */
  33598. set: function (value) {
  33599. this._shadowsExposure = value;
  33600. this._dirty = true;
  33601. },
  33602. enumerable: true,
  33603. configurable: true
  33604. });
  33605. ColorCurves.prototype.getClassName = function () {
  33606. return "ColorCurves";
  33607. };
  33608. /**
  33609. * Binds the color curves to the shader.
  33610. * @param colorCurves The color curve to bind
  33611. * @param effect The effect to bind to
  33612. */
  33613. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  33614. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  33615. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  33616. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  33617. if (colorCurves._dirty) {
  33618. colorCurves._dirty = false;
  33619. // Fill in global info.
  33620. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  33621. // Compute highlights info.
  33622. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  33623. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  33624. // Compute midtones info.
  33625. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  33626. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  33627. // Compute shadows info.
  33628. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  33629. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  33630. // Compute deltas (neutral is midtones).
  33631. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  33632. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  33633. }
  33634. if (effect) {
  33635. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  33636. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  33637. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  33638. }
  33639. };
  33640. /**
  33641. * Prepare the list of uniforms associated with the ColorCurves effects.
  33642. * @param uniformsList The list of uniforms used in the effect
  33643. */
  33644. ColorCurves.PrepareUniforms = function (uniformsList) {
  33645. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  33646. };
  33647. /**
  33648. * Returns color grading data based on a hue, density, saturation and exposure value.
  33649. * @param filterHue The hue of the color filter.
  33650. * @param filterDensity The density of the color filter.
  33651. * @param saturation The saturation.
  33652. * @param exposure The exposure.
  33653. * @param result The result data container.
  33654. */
  33655. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  33656. if (hue == null) {
  33657. return;
  33658. }
  33659. hue = ColorCurves.clamp(hue, 0, 360);
  33660. density = ColorCurves.clamp(density, -100, 100);
  33661. saturation = ColorCurves.clamp(saturation, -100, 100);
  33662. exposure = ColorCurves.clamp(exposure, -100, 100);
  33663. // Remap the slider/config filter density with non-linear mapping and also scale by half
  33664. // so that the maximum filter density is only 50% control. This provides fine control
  33665. // for small values and reasonable range.
  33666. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  33667. density *= 0.5;
  33668. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  33669. if (density < 0) {
  33670. density *= -1;
  33671. hue = (hue + 180) % 360;
  33672. }
  33673. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  33674. result.scaleToRef(2, result);
  33675. result.a = 1 + 0.01 * saturation;
  33676. };
  33677. /**
  33678. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  33679. * @param value The input slider value in range [-100,100].
  33680. * @returns Adjusted value.
  33681. */
  33682. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  33683. value /= 100;
  33684. var x = Math.abs(value);
  33685. x = Math.pow(x, 2);
  33686. if (value < 0) {
  33687. x *= -1;
  33688. }
  33689. x *= 100;
  33690. return x;
  33691. };
  33692. /**
  33693. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  33694. * @param hue The hue (H) input.
  33695. * @param saturation The saturation (S) input.
  33696. * @param brightness The brightness (B) input.
  33697. * @result An RGBA color represented as Vector4.
  33698. */
  33699. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  33700. var h = ColorCurves.clamp(hue, 0, 360);
  33701. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  33702. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  33703. if (s === 0) {
  33704. result.r = v;
  33705. result.g = v;
  33706. result.b = v;
  33707. }
  33708. else {
  33709. // sector 0 to 5
  33710. h /= 60;
  33711. var i = Math.floor(h);
  33712. // fractional part of h
  33713. var f = h - i;
  33714. var p = v * (1 - s);
  33715. var q = v * (1 - s * f);
  33716. var t = v * (1 - s * (1 - f));
  33717. switch (i) {
  33718. case 0:
  33719. result.r = v;
  33720. result.g = t;
  33721. result.b = p;
  33722. break;
  33723. case 1:
  33724. result.r = q;
  33725. result.g = v;
  33726. result.b = p;
  33727. break;
  33728. case 2:
  33729. result.r = p;
  33730. result.g = v;
  33731. result.b = t;
  33732. break;
  33733. case 3:
  33734. result.r = p;
  33735. result.g = q;
  33736. result.b = v;
  33737. break;
  33738. case 4:
  33739. result.r = t;
  33740. result.g = p;
  33741. result.b = v;
  33742. break;
  33743. default:// case 5:
  33744. result.r = v;
  33745. result.g = p;
  33746. result.b = q;
  33747. break;
  33748. }
  33749. }
  33750. result.a = 1;
  33751. };
  33752. /**
  33753. * Returns a value clamped between min and max
  33754. * @param value The value to clamp
  33755. * @param min The minimum of value
  33756. * @param max The maximum of value
  33757. * @returns The clamped value.
  33758. */
  33759. ColorCurves.clamp = function (value, min, max) {
  33760. return Math.min(Math.max(value, min), max);
  33761. };
  33762. /**
  33763. * Clones the current color curve instance.
  33764. * @return The cloned curves
  33765. */
  33766. ColorCurves.prototype.clone = function () {
  33767. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  33768. };
  33769. /**
  33770. * Serializes the current color curve instance to a json representation.
  33771. * @return a JSON representation
  33772. */
  33773. ColorCurves.prototype.serialize = function () {
  33774. return BABYLON.SerializationHelper.Serialize(this);
  33775. };
  33776. /**
  33777. * Parses the color curve from a json representation.
  33778. * @param source the JSON source to parse
  33779. * @return The parsed curves
  33780. */
  33781. ColorCurves.Parse = function (source) {
  33782. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  33783. };
  33784. __decorate([
  33785. BABYLON.serialize()
  33786. ], ColorCurves.prototype, "_globalHue", void 0);
  33787. __decorate([
  33788. BABYLON.serialize()
  33789. ], ColorCurves.prototype, "_globalDensity", void 0);
  33790. __decorate([
  33791. BABYLON.serialize()
  33792. ], ColorCurves.prototype, "_globalSaturation", void 0);
  33793. __decorate([
  33794. BABYLON.serialize()
  33795. ], ColorCurves.prototype, "_globalExposure", void 0);
  33796. __decorate([
  33797. BABYLON.serialize()
  33798. ], ColorCurves.prototype, "_highlightsHue", void 0);
  33799. __decorate([
  33800. BABYLON.serialize()
  33801. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  33802. __decorate([
  33803. BABYLON.serialize()
  33804. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  33805. __decorate([
  33806. BABYLON.serialize()
  33807. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  33808. __decorate([
  33809. BABYLON.serialize()
  33810. ], ColorCurves.prototype, "_midtonesHue", void 0);
  33811. __decorate([
  33812. BABYLON.serialize()
  33813. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  33814. __decorate([
  33815. BABYLON.serialize()
  33816. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  33817. __decorate([
  33818. BABYLON.serialize()
  33819. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  33820. return ColorCurves;
  33821. }());
  33822. BABYLON.ColorCurves = ColorCurves;
  33823. })(BABYLON || (BABYLON = {}));
  33824. //# sourceMappingURL=babylon.colorCurves.js.map
  33825. var BABYLON;
  33826. (function (BABYLON) {
  33827. var StandardMaterialDefines = /** @class */ (function (_super) {
  33828. __extends(StandardMaterialDefines, _super);
  33829. function StandardMaterialDefines() {
  33830. var _this = _super.call(this) || this;
  33831. _this.MAINUV1 = false;
  33832. _this.MAINUV2 = false;
  33833. _this.DIFFUSE = false;
  33834. _this.DIFFUSEDIRECTUV = 0;
  33835. _this.AMBIENT = false;
  33836. _this.AMBIENTDIRECTUV = 0;
  33837. _this.OPACITY = false;
  33838. _this.OPACITYDIRECTUV = 0;
  33839. _this.OPACITYRGB = false;
  33840. _this.REFLECTION = false;
  33841. _this.EMISSIVE = false;
  33842. _this.EMISSIVEDIRECTUV = 0;
  33843. _this.SPECULAR = false;
  33844. _this.SPECULARDIRECTUV = 0;
  33845. _this.BUMP = false;
  33846. _this.BUMPDIRECTUV = 0;
  33847. _this.PARALLAX = false;
  33848. _this.PARALLAXOCCLUSION = false;
  33849. _this.SPECULAROVERALPHA = false;
  33850. _this.CLIPPLANE = false;
  33851. _this.ALPHATEST = false;
  33852. _this.DEPTHPREPASS = false;
  33853. _this.ALPHAFROMDIFFUSE = false;
  33854. _this.POINTSIZE = false;
  33855. _this.FOG = false;
  33856. _this.SPECULARTERM = false;
  33857. _this.DIFFUSEFRESNEL = false;
  33858. _this.OPACITYFRESNEL = false;
  33859. _this.REFLECTIONFRESNEL = false;
  33860. _this.REFRACTIONFRESNEL = false;
  33861. _this.EMISSIVEFRESNEL = false;
  33862. _this.FRESNEL = false;
  33863. _this.NORMAL = false;
  33864. _this.UV1 = false;
  33865. _this.UV2 = false;
  33866. _this.VERTEXCOLOR = false;
  33867. _this.VERTEXALPHA = false;
  33868. _this.NUM_BONE_INFLUENCERS = 0;
  33869. _this.BonesPerMesh = 0;
  33870. _this.INSTANCES = false;
  33871. _this.GLOSSINESS = false;
  33872. _this.ROUGHNESS = false;
  33873. _this.EMISSIVEASILLUMINATION = false;
  33874. _this.LINKEMISSIVEWITHDIFFUSE = false;
  33875. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  33876. _this.LIGHTMAP = false;
  33877. _this.LIGHTMAPDIRECTUV = 0;
  33878. _this.USELIGHTMAPASSHADOWMAP = false;
  33879. _this.REFLECTIONMAP_3D = false;
  33880. _this.REFLECTIONMAP_SPHERICAL = false;
  33881. _this.REFLECTIONMAP_PLANAR = false;
  33882. _this.REFLECTIONMAP_CUBIC = false;
  33883. _this.REFLECTIONMAP_PROJECTION = false;
  33884. _this.REFLECTIONMAP_SKYBOX = false;
  33885. _this.REFLECTIONMAP_EXPLICIT = false;
  33886. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  33887. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  33888. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  33889. _this.INVERTCUBICMAP = false;
  33890. _this.LOGARITHMICDEPTH = false;
  33891. _this.REFRACTION = false;
  33892. _this.REFRACTIONMAP_3D = false;
  33893. _this.REFLECTIONOVERALPHA = false;
  33894. _this.TWOSIDEDLIGHTING = false;
  33895. _this.SHADOWFLOAT = false;
  33896. _this.MORPHTARGETS = false;
  33897. _this.MORPHTARGETS_NORMAL = false;
  33898. _this.MORPHTARGETS_TANGENT = false;
  33899. _this.NUM_MORPH_INFLUENCERS = 0;
  33900. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  33901. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  33902. _this.IMAGEPROCESSING = false;
  33903. _this.VIGNETTE = false;
  33904. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  33905. _this.VIGNETTEBLENDMODEOPAQUE = false;
  33906. _this.TONEMAPPING = false;
  33907. _this.CONTRAST = false;
  33908. _this.COLORCURVES = false;
  33909. _this.COLORGRADING = false;
  33910. _this.COLORGRADING3D = false;
  33911. _this.SAMPLER3DGREENDEPTH = false;
  33912. _this.SAMPLER3DBGRMAP = false;
  33913. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  33914. _this.EXPOSURE = false;
  33915. _this.rebuild();
  33916. return _this;
  33917. }
  33918. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  33919. var modes = [
  33920. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  33921. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  33922. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  33923. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  33924. ];
  33925. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  33926. var mode = modes_1[_i];
  33927. this[mode] = (mode === modeToEnable);
  33928. }
  33929. };
  33930. return StandardMaterialDefines;
  33931. }(BABYLON.MaterialDefines));
  33932. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  33933. var StandardMaterial = /** @class */ (function (_super) {
  33934. __extends(StandardMaterial, _super);
  33935. function StandardMaterial(name, scene) {
  33936. var _this = _super.call(this, name, scene) || this;
  33937. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  33938. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  33939. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  33940. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  33941. _this.specularPower = 64;
  33942. _this._useAlphaFromDiffuseTexture = false;
  33943. _this._useEmissiveAsIllumination = false;
  33944. _this._linkEmissiveWithDiffuse = false;
  33945. _this._useSpecularOverAlpha = false;
  33946. _this._useReflectionOverAlpha = false;
  33947. _this._disableLighting = false;
  33948. _this._useParallax = false;
  33949. _this._useParallaxOcclusion = false;
  33950. _this.parallaxScaleBias = 0.05;
  33951. _this._roughness = 0;
  33952. _this.indexOfRefraction = 0.98;
  33953. _this.invertRefractionY = true;
  33954. _this._useLightmapAsShadowmap = false;
  33955. _this._useReflectionFresnelFromSpecular = false;
  33956. _this._useGlossinessFromSpecularMapAlpha = false;
  33957. _this._maxSimultaneousLights = 4;
  33958. /**
  33959. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  33960. */
  33961. _this._invertNormalMapX = false;
  33962. /**
  33963. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  33964. */
  33965. _this._invertNormalMapY = false;
  33966. /**
  33967. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  33968. */
  33969. _this._twoSidedLighting = false;
  33970. _this._renderTargets = new BABYLON.SmartArray(16);
  33971. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  33972. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  33973. // Setup the default processing configuration to the scene.
  33974. _this._attachImageProcessingConfiguration(null);
  33975. _this.getRenderTargetTextures = function () {
  33976. _this._renderTargets.reset();
  33977. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  33978. _this._renderTargets.push(_this._reflectionTexture);
  33979. }
  33980. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  33981. _this._renderTargets.push(_this._refractionTexture);
  33982. }
  33983. return _this._renderTargets;
  33984. };
  33985. return _this;
  33986. }
  33987. ;
  33988. ;
  33989. ;
  33990. ;
  33991. ;
  33992. ;
  33993. ;
  33994. ;
  33995. ;
  33996. ;
  33997. ;
  33998. ;
  33999. ;
  34000. ;
  34001. ;
  34002. ;
  34003. ;
  34004. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  34005. /**
  34006. * Gets the image processing configuration used either in this material.
  34007. */
  34008. get: function () {
  34009. return this._imageProcessingConfiguration;
  34010. },
  34011. /**
  34012. * Sets the Default image processing configuration used either in the this material.
  34013. *
  34014. * If sets to null, the scene one is in use.
  34015. */
  34016. set: function (value) {
  34017. this._attachImageProcessingConfiguration(value);
  34018. // Ensure the effect will be rebuilt.
  34019. this._markAllSubMeshesAsTexturesDirty();
  34020. },
  34021. enumerable: true,
  34022. configurable: true
  34023. });
  34024. /**
  34025. * Attaches a new image processing configuration to the Standard Material.
  34026. * @param configuration
  34027. */
  34028. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  34029. var _this = this;
  34030. if (configuration === this._imageProcessingConfiguration) {
  34031. return;
  34032. }
  34033. // Detaches observer.
  34034. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34035. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34036. }
  34037. // Pick the scene configuration if needed.
  34038. if (!configuration) {
  34039. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  34040. }
  34041. else {
  34042. this._imageProcessingConfiguration = configuration;
  34043. }
  34044. // Attaches observer.
  34045. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  34046. _this._markAllSubMeshesAsImageProcessingDirty();
  34047. });
  34048. };
  34049. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  34050. /**
  34051. * Gets wether the color curves effect is enabled.
  34052. */
  34053. get: function () {
  34054. return this.imageProcessingConfiguration.colorCurvesEnabled;
  34055. },
  34056. /**
  34057. * Sets wether the color curves effect is enabled.
  34058. */
  34059. set: function (value) {
  34060. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  34061. },
  34062. enumerable: true,
  34063. configurable: true
  34064. });
  34065. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  34066. /**
  34067. * Gets wether the color grading effect is enabled.
  34068. */
  34069. get: function () {
  34070. return this.imageProcessingConfiguration.colorGradingEnabled;
  34071. },
  34072. /**
  34073. * Gets wether the color grading effect is enabled.
  34074. */
  34075. set: function (value) {
  34076. this.imageProcessingConfiguration.colorGradingEnabled = value;
  34077. },
  34078. enumerable: true,
  34079. configurable: true
  34080. });
  34081. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  34082. /**
  34083. * Gets wether tonemapping is enabled or not.
  34084. */
  34085. get: function () {
  34086. return this._imageProcessingConfiguration.toneMappingEnabled;
  34087. },
  34088. /**
  34089. * Sets wether tonemapping is enabled or not
  34090. */
  34091. set: function (value) {
  34092. this._imageProcessingConfiguration.toneMappingEnabled = value;
  34093. },
  34094. enumerable: true,
  34095. configurable: true
  34096. });
  34097. ;
  34098. ;
  34099. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  34100. /**
  34101. * The camera exposure used on this material.
  34102. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  34103. * This corresponds to a photographic exposure.
  34104. */
  34105. get: function () {
  34106. return this._imageProcessingConfiguration.exposure;
  34107. },
  34108. /**
  34109. * The camera exposure used on this material.
  34110. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  34111. * This corresponds to a photographic exposure.
  34112. */
  34113. set: function (value) {
  34114. this._imageProcessingConfiguration.exposure = value;
  34115. },
  34116. enumerable: true,
  34117. configurable: true
  34118. });
  34119. ;
  34120. ;
  34121. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  34122. /**
  34123. * Gets The camera contrast used on this material.
  34124. */
  34125. get: function () {
  34126. return this._imageProcessingConfiguration.contrast;
  34127. },
  34128. /**
  34129. * Sets The camera contrast used on this material.
  34130. */
  34131. set: function (value) {
  34132. this._imageProcessingConfiguration.contrast = value;
  34133. },
  34134. enumerable: true,
  34135. configurable: true
  34136. });
  34137. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  34138. /**
  34139. * Gets the Color Grading 2D Lookup Texture.
  34140. */
  34141. get: function () {
  34142. return this._imageProcessingConfiguration.colorGradingTexture;
  34143. },
  34144. /**
  34145. * Sets the Color Grading 2D Lookup Texture.
  34146. */
  34147. set: function (value) {
  34148. this._imageProcessingConfiguration.colorGradingTexture = value;
  34149. },
  34150. enumerable: true,
  34151. configurable: true
  34152. });
  34153. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  34154. /**
  34155. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34156. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34157. * 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;
  34158. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34159. */
  34160. get: function () {
  34161. return this._imageProcessingConfiguration.colorCurves;
  34162. },
  34163. /**
  34164. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34165. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34166. * 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;
  34167. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34168. */
  34169. set: function (value) {
  34170. this._imageProcessingConfiguration.colorCurves = value;
  34171. },
  34172. enumerable: true,
  34173. configurable: true
  34174. });
  34175. StandardMaterial.prototype.getClassName = function () {
  34176. return "StandardMaterial";
  34177. };
  34178. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  34179. get: function () {
  34180. return this._useLogarithmicDepth;
  34181. },
  34182. set: function (value) {
  34183. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  34184. this._markAllSubMeshesAsMiscDirty();
  34185. },
  34186. enumerable: true,
  34187. configurable: true
  34188. });
  34189. StandardMaterial.prototype.needAlphaBlending = function () {
  34190. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  34191. };
  34192. StandardMaterial.prototype.needAlphaTesting = function () {
  34193. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  34194. };
  34195. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  34196. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  34197. };
  34198. StandardMaterial.prototype.getAlphaTestTexture = function () {
  34199. return this._diffuseTexture;
  34200. };
  34201. /**
  34202. * Child classes can use it to update shaders
  34203. */
  34204. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34205. if (useInstances === void 0) { useInstances = false; }
  34206. if (subMesh.effect && this.isFrozen) {
  34207. if (this._wasPreviouslyReady && subMesh.effect) {
  34208. return true;
  34209. }
  34210. }
  34211. if (!subMesh._materialDefines) {
  34212. subMesh._materialDefines = new StandardMaterialDefines();
  34213. }
  34214. var scene = this.getScene();
  34215. var defines = subMesh._materialDefines;
  34216. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  34217. if (defines._renderId === scene.getRenderId()) {
  34218. return true;
  34219. }
  34220. }
  34221. var engine = scene.getEngine();
  34222. // Lights
  34223. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  34224. // Textures
  34225. if (defines._areTexturesDirty) {
  34226. defines._needUVs = false;
  34227. defines.MAINUV1 = false;
  34228. defines.MAINUV2 = false;
  34229. if (scene.texturesEnabled) {
  34230. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34231. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  34232. return false;
  34233. }
  34234. else {
  34235. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  34236. }
  34237. }
  34238. else {
  34239. defines.DIFFUSE = false;
  34240. }
  34241. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34242. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  34243. return false;
  34244. }
  34245. else {
  34246. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  34247. }
  34248. }
  34249. else {
  34250. defines.AMBIENT = false;
  34251. }
  34252. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34253. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  34254. return false;
  34255. }
  34256. else {
  34257. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  34258. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  34259. }
  34260. }
  34261. else {
  34262. defines.OPACITY = false;
  34263. }
  34264. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34265. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  34266. return false;
  34267. }
  34268. else {
  34269. defines._needNormals = true;
  34270. defines.REFLECTION = true;
  34271. defines.ROUGHNESS = (this._roughness > 0);
  34272. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  34273. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  34274. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  34275. switch (this._reflectionTexture.coordinatesMode) {
  34276. case BABYLON.Texture.CUBIC_MODE:
  34277. case BABYLON.Texture.INVCUBIC_MODE:
  34278. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  34279. break;
  34280. case BABYLON.Texture.EXPLICIT_MODE:
  34281. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  34282. break;
  34283. case BABYLON.Texture.PLANAR_MODE:
  34284. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  34285. break;
  34286. case BABYLON.Texture.PROJECTION_MODE:
  34287. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  34288. break;
  34289. case BABYLON.Texture.SKYBOX_MODE:
  34290. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  34291. break;
  34292. case BABYLON.Texture.SPHERICAL_MODE:
  34293. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  34294. break;
  34295. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  34296. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  34297. break;
  34298. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  34299. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  34300. break;
  34301. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  34302. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  34303. break;
  34304. }
  34305. }
  34306. }
  34307. else {
  34308. defines.REFLECTION = false;
  34309. }
  34310. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34311. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  34312. return false;
  34313. }
  34314. else {
  34315. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  34316. }
  34317. }
  34318. else {
  34319. defines.EMISSIVE = false;
  34320. }
  34321. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34322. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  34323. return false;
  34324. }
  34325. else {
  34326. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  34327. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  34328. }
  34329. }
  34330. else {
  34331. defines.LIGHTMAP = false;
  34332. }
  34333. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34334. if (!this._specularTexture.isReadyOrNotBlocking()) {
  34335. return false;
  34336. }
  34337. else {
  34338. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  34339. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  34340. }
  34341. }
  34342. else {
  34343. defines.SPECULAR = false;
  34344. }
  34345. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  34346. // Bump texure can not be not blocking.
  34347. if (!this._bumpTexture.isReady()) {
  34348. return false;
  34349. }
  34350. else {
  34351. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  34352. defines.PARALLAX = this._useParallax;
  34353. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  34354. }
  34355. }
  34356. else {
  34357. defines.BUMP = false;
  34358. }
  34359. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34360. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  34361. return false;
  34362. }
  34363. else {
  34364. defines._needUVs = true;
  34365. defines.REFRACTION = true;
  34366. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  34367. }
  34368. }
  34369. else {
  34370. defines.REFRACTION = false;
  34371. }
  34372. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  34373. }
  34374. else {
  34375. defines.DIFFUSE = false;
  34376. defines.AMBIENT = false;
  34377. defines.OPACITY = false;
  34378. defines.REFLECTION = false;
  34379. defines.EMISSIVE = false;
  34380. defines.LIGHTMAP = false;
  34381. defines.BUMP = false;
  34382. defines.REFRACTION = false;
  34383. }
  34384. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  34385. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  34386. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  34387. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  34388. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  34389. }
  34390. if (defines._areImageProcessingDirty) {
  34391. if (!this._imageProcessingConfiguration.isReady()) {
  34392. return false;
  34393. }
  34394. this._imageProcessingConfiguration.prepareDefines(defines);
  34395. }
  34396. if (defines._areFresnelDirty) {
  34397. if (StandardMaterial.FresnelEnabled) {
  34398. // Fresnel
  34399. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  34400. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  34401. this._reflectionFresnelParameters) {
  34402. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  34403. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  34404. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  34405. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  34406. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  34407. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  34408. defines._needNormals = true;
  34409. defines.FRESNEL = true;
  34410. }
  34411. }
  34412. else {
  34413. defines.FRESNEL = false;
  34414. }
  34415. }
  34416. // Misc.
  34417. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  34418. // Attribs
  34419. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  34420. // Values that need to be evaluated on every frame
  34421. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  34422. // Get correct effect
  34423. if (defines.isDirty) {
  34424. defines.markAsProcessed();
  34425. scene.resetCachedMaterial();
  34426. // Fallbacks
  34427. var fallbacks = new BABYLON.EffectFallbacks();
  34428. if (defines.REFLECTION) {
  34429. fallbacks.addFallback(0, "REFLECTION");
  34430. }
  34431. if (defines.SPECULAR) {
  34432. fallbacks.addFallback(0, "SPECULAR");
  34433. }
  34434. if (defines.BUMP) {
  34435. fallbacks.addFallback(0, "BUMP");
  34436. }
  34437. if (defines.PARALLAX) {
  34438. fallbacks.addFallback(1, "PARALLAX");
  34439. }
  34440. if (defines.PARALLAXOCCLUSION) {
  34441. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  34442. }
  34443. if (defines.SPECULAROVERALPHA) {
  34444. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  34445. }
  34446. if (defines.FOG) {
  34447. fallbacks.addFallback(1, "FOG");
  34448. }
  34449. if (defines.POINTSIZE) {
  34450. fallbacks.addFallback(0, "POINTSIZE");
  34451. }
  34452. if (defines.LOGARITHMICDEPTH) {
  34453. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  34454. }
  34455. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  34456. if (defines.SPECULARTERM) {
  34457. fallbacks.addFallback(0, "SPECULARTERM");
  34458. }
  34459. if (defines.DIFFUSEFRESNEL) {
  34460. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  34461. }
  34462. if (defines.OPACITYFRESNEL) {
  34463. fallbacks.addFallback(2, "OPACITYFRESNEL");
  34464. }
  34465. if (defines.REFLECTIONFRESNEL) {
  34466. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  34467. }
  34468. if (defines.EMISSIVEFRESNEL) {
  34469. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  34470. }
  34471. if (defines.FRESNEL) {
  34472. fallbacks.addFallback(4, "FRESNEL");
  34473. }
  34474. //Attributes
  34475. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34476. if (defines.NORMAL) {
  34477. attribs.push(BABYLON.VertexBuffer.NormalKind);
  34478. }
  34479. if (defines.UV1) {
  34480. attribs.push(BABYLON.VertexBuffer.UVKind);
  34481. }
  34482. if (defines.UV2) {
  34483. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34484. }
  34485. if (defines.VERTEXCOLOR) {
  34486. attribs.push(BABYLON.VertexBuffer.ColorKind);
  34487. }
  34488. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  34489. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  34490. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  34491. var shaderName = "default";
  34492. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  34493. "vFogInfos", "vFogColor", "pointSize",
  34494. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  34495. "mBones",
  34496. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  34497. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  34498. "logarithmicDepthConstant", "vTangentSpaceParams"
  34499. ];
  34500. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  34501. var uniformBuffers = ["Material", "Scene"];
  34502. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  34503. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  34504. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  34505. uniformsNames: uniforms,
  34506. uniformBuffersNames: uniformBuffers,
  34507. samplers: samplers,
  34508. defines: defines,
  34509. maxSimultaneousLights: this._maxSimultaneousLights
  34510. });
  34511. if (this.customShaderNameResolve) {
  34512. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  34513. }
  34514. var join = defines.toString();
  34515. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  34516. attributes: attribs,
  34517. uniformsNames: uniforms,
  34518. uniformBuffersNames: uniformBuffers,
  34519. samplers: samplers,
  34520. defines: join,
  34521. fallbacks: fallbacks,
  34522. onCompiled: this.onCompiled,
  34523. onError: this.onError,
  34524. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  34525. }, engine), defines);
  34526. this.buildUniformLayout();
  34527. }
  34528. if (!subMesh.effect || !subMesh.effect.isReady()) {
  34529. return false;
  34530. }
  34531. defines._renderId = scene.getRenderId();
  34532. this._wasPreviouslyReady = true;
  34533. return true;
  34534. };
  34535. StandardMaterial.prototype.buildUniformLayout = function () {
  34536. // Order is important !
  34537. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  34538. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  34539. this._uniformBuffer.addUniform("opacityParts", 4);
  34540. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  34541. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  34542. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  34543. this._uniformBuffer.addUniform("refractionRightColor", 4);
  34544. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  34545. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  34546. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  34547. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  34548. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  34549. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  34550. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  34551. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  34552. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  34553. this._uniformBuffer.addUniform("vBumpInfos", 3);
  34554. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  34555. this._uniformBuffer.addUniform("ambientMatrix", 16);
  34556. this._uniformBuffer.addUniform("opacityMatrix", 16);
  34557. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  34558. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  34559. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  34560. this._uniformBuffer.addUniform("specularMatrix", 16);
  34561. this._uniformBuffer.addUniform("bumpMatrix", 16);
  34562. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  34563. this._uniformBuffer.addUniform("refractionMatrix", 16);
  34564. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  34565. this._uniformBuffer.addUniform("vSpecularColor", 4);
  34566. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  34567. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  34568. this._uniformBuffer.addUniform("pointSize", 1);
  34569. this._uniformBuffer.create();
  34570. };
  34571. StandardMaterial.prototype.unbind = function () {
  34572. if (this._activeEffect) {
  34573. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  34574. this._activeEffect.setTexture("reflection2DSampler", null);
  34575. }
  34576. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  34577. this._activeEffect.setTexture("refraction2DSampler", null);
  34578. }
  34579. }
  34580. _super.prototype.unbind.call(this);
  34581. };
  34582. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34583. var scene = this.getScene();
  34584. var defines = subMesh._materialDefines;
  34585. if (!defines) {
  34586. return;
  34587. }
  34588. var effect = subMesh.effect;
  34589. if (!effect) {
  34590. return;
  34591. }
  34592. this._activeEffect = effect;
  34593. // Matrices
  34594. this.bindOnlyWorldMatrix(world);
  34595. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  34596. // Bones
  34597. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  34598. if (mustRebind) {
  34599. this._uniformBuffer.bindToEffect(effect, "Material");
  34600. this.bindViewProjection(effect);
  34601. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  34602. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  34603. // Fresnel
  34604. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  34605. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  34606. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  34607. }
  34608. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  34609. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  34610. }
  34611. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  34612. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  34613. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  34614. }
  34615. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  34616. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  34617. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  34618. }
  34619. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  34620. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  34621. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  34622. }
  34623. }
  34624. // Textures
  34625. if (scene.texturesEnabled) {
  34626. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34627. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  34628. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  34629. }
  34630. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34631. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  34632. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  34633. }
  34634. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34635. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  34636. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  34637. }
  34638. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34639. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  34640. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  34641. }
  34642. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34643. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  34644. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  34645. }
  34646. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34647. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  34648. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  34649. }
  34650. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34651. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  34652. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  34653. }
  34654. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  34655. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  34656. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  34657. if (scene._mirroredCameraPosition) {
  34658. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  34659. }
  34660. else {
  34661. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  34662. }
  34663. }
  34664. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34665. var depth = 1.0;
  34666. if (!this._refractionTexture.isCube) {
  34667. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  34668. if (this._refractionTexture.depth) {
  34669. depth = this._refractionTexture.depth;
  34670. }
  34671. }
  34672. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  34673. }
  34674. }
  34675. // Point size
  34676. if (this.pointsCloud) {
  34677. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  34678. }
  34679. if (defines.SPECULARTERM) {
  34680. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  34681. }
  34682. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  34683. // Diffuse
  34684. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  34685. }
  34686. // Textures
  34687. if (scene.texturesEnabled) {
  34688. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34689. effect.setTexture("diffuseSampler", this._diffuseTexture);
  34690. }
  34691. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34692. effect.setTexture("ambientSampler", this._ambientTexture);
  34693. }
  34694. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34695. effect.setTexture("opacitySampler", this._opacityTexture);
  34696. }
  34697. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34698. if (this._reflectionTexture.isCube) {
  34699. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  34700. }
  34701. else {
  34702. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  34703. }
  34704. }
  34705. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34706. effect.setTexture("emissiveSampler", this._emissiveTexture);
  34707. }
  34708. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34709. effect.setTexture("lightmapSampler", this._lightmapTexture);
  34710. }
  34711. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34712. effect.setTexture("specularSampler", this._specularTexture);
  34713. }
  34714. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  34715. effect.setTexture("bumpSampler", this._bumpTexture);
  34716. }
  34717. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34718. var depth = 1.0;
  34719. if (this._refractionTexture.isCube) {
  34720. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  34721. }
  34722. else {
  34723. effect.setTexture("refraction2DSampler", this._refractionTexture);
  34724. }
  34725. }
  34726. }
  34727. // Clip plane
  34728. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  34729. // Colors
  34730. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  34731. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  34732. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  34733. }
  34734. if (mustRebind || !this.isFrozen) {
  34735. // Lights
  34736. if (scene.lightsEnabled && !this._disableLighting) {
  34737. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  34738. }
  34739. // View
  34740. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  34741. this.bindView(effect);
  34742. }
  34743. // Fog
  34744. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  34745. // Morph targets
  34746. if (defines.NUM_MORPH_INFLUENCERS) {
  34747. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  34748. }
  34749. // Log. depth
  34750. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  34751. // image processing
  34752. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  34753. this._imageProcessingConfiguration.bind(this._activeEffect);
  34754. }
  34755. }
  34756. this._uniformBuffer.update();
  34757. this._afterBind(mesh, this._activeEffect);
  34758. };
  34759. StandardMaterial.prototype.getAnimatables = function () {
  34760. var results = [];
  34761. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  34762. results.push(this._diffuseTexture);
  34763. }
  34764. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  34765. results.push(this._ambientTexture);
  34766. }
  34767. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  34768. results.push(this._opacityTexture);
  34769. }
  34770. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  34771. results.push(this._reflectionTexture);
  34772. }
  34773. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  34774. results.push(this._emissiveTexture);
  34775. }
  34776. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  34777. results.push(this._specularTexture);
  34778. }
  34779. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  34780. results.push(this._bumpTexture);
  34781. }
  34782. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  34783. results.push(this._lightmapTexture);
  34784. }
  34785. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  34786. results.push(this._refractionTexture);
  34787. }
  34788. return results;
  34789. };
  34790. StandardMaterial.prototype.getActiveTextures = function () {
  34791. var activeTextures = _super.prototype.getActiveTextures.call(this);
  34792. if (this._diffuseTexture) {
  34793. activeTextures.push(this._diffuseTexture);
  34794. }
  34795. if (this._ambientTexture) {
  34796. activeTextures.push(this._ambientTexture);
  34797. }
  34798. if (this._opacityTexture) {
  34799. activeTextures.push(this._opacityTexture);
  34800. }
  34801. if (this._reflectionTexture) {
  34802. activeTextures.push(this._reflectionTexture);
  34803. }
  34804. if (this._emissiveTexture) {
  34805. activeTextures.push(this._emissiveTexture);
  34806. }
  34807. if (this._specularTexture) {
  34808. activeTextures.push(this._specularTexture);
  34809. }
  34810. if (this._bumpTexture) {
  34811. activeTextures.push(this._bumpTexture);
  34812. }
  34813. if (this._lightmapTexture) {
  34814. activeTextures.push(this._lightmapTexture);
  34815. }
  34816. if (this._refractionTexture) {
  34817. activeTextures.push(this._refractionTexture);
  34818. }
  34819. return activeTextures;
  34820. };
  34821. StandardMaterial.prototype.hasTexture = function (texture) {
  34822. if (_super.prototype.hasTexture.call(this, texture)) {
  34823. return true;
  34824. }
  34825. if (this._diffuseTexture === texture) {
  34826. return true;
  34827. }
  34828. if (this._ambientTexture === texture) {
  34829. return true;
  34830. }
  34831. if (this._opacityTexture === texture) {
  34832. return true;
  34833. }
  34834. if (this._reflectionTexture === texture) {
  34835. return true;
  34836. }
  34837. if (this._emissiveTexture === texture) {
  34838. return true;
  34839. }
  34840. if (this._specularTexture === texture) {
  34841. return true;
  34842. }
  34843. if (this._bumpTexture === texture) {
  34844. return true;
  34845. }
  34846. if (this._lightmapTexture === texture) {
  34847. return true;
  34848. }
  34849. if (this._refractionTexture === texture) {
  34850. return true;
  34851. }
  34852. return false;
  34853. };
  34854. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  34855. if (forceDisposeTextures) {
  34856. if (this._diffuseTexture) {
  34857. this._diffuseTexture.dispose();
  34858. }
  34859. if (this._ambientTexture) {
  34860. this._ambientTexture.dispose();
  34861. }
  34862. if (this._opacityTexture) {
  34863. this._opacityTexture.dispose();
  34864. }
  34865. if (this._reflectionTexture) {
  34866. this._reflectionTexture.dispose();
  34867. }
  34868. if (this._emissiveTexture) {
  34869. this._emissiveTexture.dispose();
  34870. }
  34871. if (this._specularTexture) {
  34872. this._specularTexture.dispose();
  34873. }
  34874. if (this._bumpTexture) {
  34875. this._bumpTexture.dispose();
  34876. }
  34877. if (this._lightmapTexture) {
  34878. this._lightmapTexture.dispose();
  34879. }
  34880. if (this._refractionTexture) {
  34881. this._refractionTexture.dispose();
  34882. }
  34883. }
  34884. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34885. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34886. }
  34887. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  34888. };
  34889. StandardMaterial.prototype.clone = function (name) {
  34890. var _this = this;
  34891. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  34892. result.name = name;
  34893. result.id = name;
  34894. return result;
  34895. };
  34896. StandardMaterial.prototype.serialize = function () {
  34897. return BABYLON.SerializationHelper.Serialize(this);
  34898. };
  34899. // Statics
  34900. StandardMaterial.Parse = function (source, scene, rootUrl) {
  34901. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  34902. };
  34903. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  34904. get: function () {
  34905. return StandardMaterial._DiffuseTextureEnabled;
  34906. },
  34907. set: function (value) {
  34908. if (StandardMaterial._DiffuseTextureEnabled === value) {
  34909. return;
  34910. }
  34911. StandardMaterial._DiffuseTextureEnabled = value;
  34912. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34913. },
  34914. enumerable: true,
  34915. configurable: true
  34916. });
  34917. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  34918. get: function () {
  34919. return StandardMaterial._AmbientTextureEnabled;
  34920. },
  34921. set: function (value) {
  34922. if (StandardMaterial._AmbientTextureEnabled === value) {
  34923. return;
  34924. }
  34925. StandardMaterial._AmbientTextureEnabled = value;
  34926. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34927. },
  34928. enumerable: true,
  34929. configurable: true
  34930. });
  34931. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  34932. get: function () {
  34933. return StandardMaterial._OpacityTextureEnabled;
  34934. },
  34935. set: function (value) {
  34936. if (StandardMaterial._OpacityTextureEnabled === value) {
  34937. return;
  34938. }
  34939. StandardMaterial._OpacityTextureEnabled = value;
  34940. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34941. },
  34942. enumerable: true,
  34943. configurable: true
  34944. });
  34945. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  34946. get: function () {
  34947. return StandardMaterial._ReflectionTextureEnabled;
  34948. },
  34949. set: function (value) {
  34950. if (StandardMaterial._ReflectionTextureEnabled === value) {
  34951. return;
  34952. }
  34953. StandardMaterial._ReflectionTextureEnabled = value;
  34954. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34955. },
  34956. enumerable: true,
  34957. configurable: true
  34958. });
  34959. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  34960. get: function () {
  34961. return StandardMaterial._EmissiveTextureEnabled;
  34962. },
  34963. set: function (value) {
  34964. if (StandardMaterial._EmissiveTextureEnabled === value) {
  34965. return;
  34966. }
  34967. StandardMaterial._EmissiveTextureEnabled = value;
  34968. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34969. },
  34970. enumerable: true,
  34971. configurable: true
  34972. });
  34973. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  34974. get: function () {
  34975. return StandardMaterial._SpecularTextureEnabled;
  34976. },
  34977. set: function (value) {
  34978. if (StandardMaterial._SpecularTextureEnabled === value) {
  34979. return;
  34980. }
  34981. StandardMaterial._SpecularTextureEnabled = value;
  34982. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34983. },
  34984. enumerable: true,
  34985. configurable: true
  34986. });
  34987. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  34988. get: function () {
  34989. return StandardMaterial._BumpTextureEnabled;
  34990. },
  34991. set: function (value) {
  34992. if (StandardMaterial._BumpTextureEnabled === value) {
  34993. return;
  34994. }
  34995. StandardMaterial._BumpTextureEnabled = value;
  34996. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34997. },
  34998. enumerable: true,
  34999. configurable: true
  35000. });
  35001. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  35002. get: function () {
  35003. return StandardMaterial._LightmapTextureEnabled;
  35004. },
  35005. set: function (value) {
  35006. if (StandardMaterial._LightmapTextureEnabled === value) {
  35007. return;
  35008. }
  35009. StandardMaterial._LightmapTextureEnabled = value;
  35010. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35011. },
  35012. enumerable: true,
  35013. configurable: true
  35014. });
  35015. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  35016. get: function () {
  35017. return StandardMaterial._RefractionTextureEnabled;
  35018. },
  35019. set: function (value) {
  35020. if (StandardMaterial._RefractionTextureEnabled === value) {
  35021. return;
  35022. }
  35023. StandardMaterial._RefractionTextureEnabled = value;
  35024. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35025. },
  35026. enumerable: true,
  35027. configurable: true
  35028. });
  35029. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  35030. get: function () {
  35031. return StandardMaterial._ColorGradingTextureEnabled;
  35032. },
  35033. set: function (value) {
  35034. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  35035. return;
  35036. }
  35037. StandardMaterial._ColorGradingTextureEnabled = value;
  35038. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35039. },
  35040. enumerable: true,
  35041. configurable: true
  35042. });
  35043. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  35044. get: function () {
  35045. return StandardMaterial._FresnelEnabled;
  35046. },
  35047. set: function (value) {
  35048. if (StandardMaterial._FresnelEnabled === value) {
  35049. return;
  35050. }
  35051. StandardMaterial._FresnelEnabled = value;
  35052. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  35053. },
  35054. enumerable: true,
  35055. configurable: true
  35056. });
  35057. // Flags used to enable or disable a type of texture for all Standard Materials
  35058. StandardMaterial._DiffuseTextureEnabled = true;
  35059. StandardMaterial._AmbientTextureEnabled = true;
  35060. StandardMaterial._OpacityTextureEnabled = true;
  35061. StandardMaterial._ReflectionTextureEnabled = true;
  35062. StandardMaterial._EmissiveTextureEnabled = true;
  35063. StandardMaterial._SpecularTextureEnabled = true;
  35064. StandardMaterial._BumpTextureEnabled = true;
  35065. StandardMaterial._LightmapTextureEnabled = true;
  35066. StandardMaterial._RefractionTextureEnabled = true;
  35067. StandardMaterial._ColorGradingTextureEnabled = true;
  35068. StandardMaterial._FresnelEnabled = true;
  35069. __decorate([
  35070. BABYLON.serializeAsTexture("diffuseTexture")
  35071. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  35072. __decorate([
  35073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35074. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  35075. __decorate([
  35076. BABYLON.serializeAsTexture("ambientTexture")
  35077. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  35078. __decorate([
  35079. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35080. ], StandardMaterial.prototype, "ambientTexture", void 0);
  35081. __decorate([
  35082. BABYLON.serializeAsTexture("opacityTexture")
  35083. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  35084. __decorate([
  35085. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35086. ], StandardMaterial.prototype, "opacityTexture", void 0);
  35087. __decorate([
  35088. BABYLON.serializeAsTexture("reflectionTexture")
  35089. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  35090. __decorate([
  35091. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35092. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  35093. __decorate([
  35094. BABYLON.serializeAsTexture("emissiveTexture")
  35095. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  35096. __decorate([
  35097. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35098. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  35099. __decorate([
  35100. BABYLON.serializeAsTexture("specularTexture")
  35101. ], StandardMaterial.prototype, "_specularTexture", void 0);
  35102. __decorate([
  35103. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35104. ], StandardMaterial.prototype, "specularTexture", void 0);
  35105. __decorate([
  35106. BABYLON.serializeAsTexture("bumpTexture")
  35107. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  35108. __decorate([
  35109. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35110. ], StandardMaterial.prototype, "bumpTexture", void 0);
  35111. __decorate([
  35112. BABYLON.serializeAsTexture("lightmapTexture")
  35113. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  35114. __decorate([
  35115. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35116. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  35117. __decorate([
  35118. BABYLON.serializeAsTexture("refractionTexture")
  35119. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  35120. __decorate([
  35121. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35122. ], StandardMaterial.prototype, "refractionTexture", void 0);
  35123. __decorate([
  35124. BABYLON.serializeAsColor3("ambient")
  35125. ], StandardMaterial.prototype, "ambientColor", void 0);
  35126. __decorate([
  35127. BABYLON.serializeAsColor3("diffuse")
  35128. ], StandardMaterial.prototype, "diffuseColor", void 0);
  35129. __decorate([
  35130. BABYLON.serializeAsColor3("specular")
  35131. ], StandardMaterial.prototype, "specularColor", void 0);
  35132. __decorate([
  35133. BABYLON.serializeAsColor3("emissive")
  35134. ], StandardMaterial.prototype, "emissiveColor", void 0);
  35135. __decorate([
  35136. BABYLON.serialize()
  35137. ], StandardMaterial.prototype, "specularPower", void 0);
  35138. __decorate([
  35139. BABYLON.serialize("useAlphaFromDiffuseTexture")
  35140. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  35141. __decorate([
  35142. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35143. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  35144. __decorate([
  35145. BABYLON.serialize("useEmissiveAsIllumination")
  35146. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  35147. __decorate([
  35148. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35149. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  35150. __decorate([
  35151. BABYLON.serialize("linkEmissiveWithDiffuse")
  35152. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  35153. __decorate([
  35154. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35155. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  35156. __decorate([
  35157. BABYLON.serialize("useSpecularOverAlpha")
  35158. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  35159. __decorate([
  35160. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35161. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  35162. __decorate([
  35163. BABYLON.serialize("useReflectionOverAlpha")
  35164. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  35165. __decorate([
  35166. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35167. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  35168. __decorate([
  35169. BABYLON.serialize("disableLighting")
  35170. ], StandardMaterial.prototype, "_disableLighting", void 0);
  35171. __decorate([
  35172. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35173. ], StandardMaterial.prototype, "disableLighting", void 0);
  35174. __decorate([
  35175. BABYLON.serialize("useParallax")
  35176. ], StandardMaterial.prototype, "_useParallax", void 0);
  35177. __decorate([
  35178. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35179. ], StandardMaterial.prototype, "useParallax", void 0);
  35180. __decorate([
  35181. BABYLON.serialize("useParallaxOcclusion")
  35182. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  35183. __decorate([
  35184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35185. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  35186. __decorate([
  35187. BABYLON.serialize()
  35188. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  35189. __decorate([
  35190. BABYLON.serialize("roughness")
  35191. ], StandardMaterial.prototype, "_roughness", void 0);
  35192. __decorate([
  35193. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35194. ], StandardMaterial.prototype, "roughness", void 0);
  35195. __decorate([
  35196. BABYLON.serialize()
  35197. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  35198. __decorate([
  35199. BABYLON.serialize()
  35200. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  35201. __decorate([
  35202. BABYLON.serialize("useLightmapAsShadowmap")
  35203. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  35204. __decorate([
  35205. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35206. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  35207. __decorate([
  35208. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  35209. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  35210. __decorate([
  35211. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35212. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  35213. __decorate([
  35214. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  35215. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  35216. __decorate([
  35217. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35218. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  35219. __decorate([
  35220. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  35221. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  35222. __decorate([
  35223. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35224. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  35225. __decorate([
  35226. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  35227. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  35228. __decorate([
  35229. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35230. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  35231. __decorate([
  35232. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  35233. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  35234. __decorate([
  35235. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35236. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  35237. __decorate([
  35238. BABYLON.serialize("useReflectionFresnelFromSpecular")
  35239. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  35240. __decorate([
  35241. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35242. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  35243. __decorate([
  35244. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  35245. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  35246. __decorate([
  35247. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35248. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  35249. __decorate([
  35250. BABYLON.serialize("maxSimultaneousLights")
  35251. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  35252. __decorate([
  35253. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35254. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  35255. __decorate([
  35256. BABYLON.serialize("invertNormalMapX")
  35257. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  35258. __decorate([
  35259. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35260. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  35261. __decorate([
  35262. BABYLON.serialize("invertNormalMapY")
  35263. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  35264. __decorate([
  35265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35266. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  35267. __decorate([
  35268. BABYLON.serialize("twoSidedLighting")
  35269. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  35270. __decorate([
  35271. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35272. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  35273. __decorate([
  35274. BABYLON.serialize()
  35275. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  35276. return StandardMaterial;
  35277. }(BABYLON.PushMaterial));
  35278. BABYLON.StandardMaterial = StandardMaterial;
  35279. })(BABYLON || (BABYLON = {}));
  35280. //# sourceMappingURL=babylon.standardMaterial.js.map
  35281. var BABYLON;
  35282. (function (BABYLON) {
  35283. var PBRMaterialDefines = /** @class */ (function (_super) {
  35284. __extends(PBRMaterialDefines, _super);
  35285. function PBRMaterialDefines() {
  35286. var _this = _super.call(this) || this;
  35287. _this.PBR = true;
  35288. _this.MAINUV1 = false;
  35289. _this.MAINUV2 = false;
  35290. _this.UV1 = false;
  35291. _this.UV2 = false;
  35292. _this.ALBEDO = false;
  35293. _this.ALBEDODIRECTUV = 0;
  35294. _this.VERTEXCOLOR = false;
  35295. _this.AMBIENT = false;
  35296. _this.AMBIENTDIRECTUV = 0;
  35297. _this.AMBIENTINGRAYSCALE = false;
  35298. _this.OPACITY = false;
  35299. _this.VERTEXALPHA = false;
  35300. _this.OPACITYDIRECTUV = 0;
  35301. _this.OPACITYRGB = false;
  35302. _this.ALPHATEST = false;
  35303. _this.DEPTHPREPASS = false;
  35304. _this.ALPHABLEND = false;
  35305. _this.ALPHAFROMALBEDO = false;
  35306. _this.ALPHATESTVALUE = 0.5;
  35307. _this.SPECULAROVERALPHA = false;
  35308. _this.RADIANCEOVERALPHA = false;
  35309. _this.ALPHAFRESNEL = false;
  35310. _this.PREMULTIPLYALPHA = false;
  35311. _this.EMISSIVE = false;
  35312. _this.EMISSIVEDIRECTUV = 0;
  35313. _this.REFLECTIVITY = false;
  35314. _this.REFLECTIVITYDIRECTUV = 0;
  35315. _this.SPECULARTERM = false;
  35316. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  35317. _this.MICROSURFACEAUTOMATIC = false;
  35318. _this.LODBASEDMICROSFURACE = false;
  35319. _this.MICROSURFACEMAP = false;
  35320. _this.MICROSURFACEMAPDIRECTUV = 0;
  35321. _this.METALLICWORKFLOW = false;
  35322. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  35323. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  35324. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  35325. _this.AOSTOREINMETALMAPRED = false;
  35326. _this.ENVIRONMENTBRDF = false;
  35327. _this.NORMAL = false;
  35328. _this.TANGENT = false;
  35329. _this.BUMP = false;
  35330. _this.BUMPDIRECTUV = 0;
  35331. _this.PARALLAX = false;
  35332. _this.PARALLAXOCCLUSION = false;
  35333. _this.NORMALXYSCALE = true;
  35334. _this.LIGHTMAP = false;
  35335. _this.LIGHTMAPDIRECTUV = 0;
  35336. _this.USELIGHTMAPASSHADOWMAP = false;
  35337. _this.REFLECTION = false;
  35338. _this.REFLECTIONMAP_3D = false;
  35339. _this.REFLECTIONMAP_SPHERICAL = false;
  35340. _this.REFLECTIONMAP_PLANAR = false;
  35341. _this.REFLECTIONMAP_CUBIC = false;
  35342. _this.REFLECTIONMAP_PROJECTION = false;
  35343. _this.REFLECTIONMAP_SKYBOX = false;
  35344. _this.REFLECTIONMAP_EXPLICIT = false;
  35345. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35346. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35347. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35348. _this.INVERTCUBICMAP = false;
  35349. _this.USESPHERICALFROMREFLECTIONMAP = false;
  35350. _this.USESPHERICALINVERTEX = false;
  35351. _this.REFLECTIONMAP_OPPOSITEZ = false;
  35352. _this.LODINREFLECTIONALPHA = false;
  35353. _this.GAMMAREFLECTION = false;
  35354. _this.RADIANCEOCCLUSION = false;
  35355. _this.HORIZONOCCLUSION = false;
  35356. _this.REFRACTION = false;
  35357. _this.REFRACTIONMAP_3D = false;
  35358. _this.REFRACTIONMAP_OPPOSITEZ = false;
  35359. _this.LODINREFRACTIONALPHA = false;
  35360. _this.GAMMAREFRACTION = false;
  35361. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  35362. _this.INSTANCES = false;
  35363. _this.NUM_BONE_INFLUENCERS = 0;
  35364. _this.BonesPerMesh = 0;
  35365. _this.NONUNIFORMSCALING = false;
  35366. _this.MORPHTARGETS = false;
  35367. _this.MORPHTARGETS_NORMAL = false;
  35368. _this.MORPHTARGETS_TANGENT = false;
  35369. _this.NUM_MORPH_INFLUENCERS = 0;
  35370. _this.IMAGEPROCESSING = false;
  35371. _this.VIGNETTE = false;
  35372. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  35373. _this.VIGNETTEBLENDMODEOPAQUE = false;
  35374. _this.TONEMAPPING = false;
  35375. _this.CONTRAST = false;
  35376. _this.COLORCURVES = false;
  35377. _this.COLORGRADING = false;
  35378. _this.COLORGRADING3D = false;
  35379. _this.SAMPLER3DGREENDEPTH = false;
  35380. _this.SAMPLER3DBGRMAP = false;
  35381. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  35382. _this.EXPOSURE = false;
  35383. _this.USEPHYSICALLIGHTFALLOFF = false;
  35384. _this.TWOSIDEDLIGHTING = false;
  35385. _this.SHADOWFLOAT = false;
  35386. _this.CLIPPLANE = false;
  35387. _this.POINTSIZE = false;
  35388. _this.FOG = false;
  35389. _this.LOGARITHMICDEPTH = false;
  35390. _this.FORCENORMALFORWARD = false;
  35391. _this.rebuild();
  35392. return _this;
  35393. }
  35394. PBRMaterialDefines.prototype.reset = function () {
  35395. _super.prototype.reset.call(this);
  35396. this.ALPHATESTVALUE = 0.5;
  35397. this.PBR = true;
  35398. };
  35399. return PBRMaterialDefines;
  35400. }(BABYLON.MaterialDefines));
  35401. /**
  35402. * The Physically based material base class of BJS.
  35403. *
  35404. * This offers the main features of a standard PBR material.
  35405. * For more information, please refer to the documentation :
  35406. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  35407. */
  35408. var PBRBaseMaterial = /** @class */ (function (_super) {
  35409. __extends(PBRBaseMaterial, _super);
  35410. /**
  35411. * Instantiates a new PBRMaterial instance.
  35412. *
  35413. * @param name The material name
  35414. * @param scene The scene the material will be use in.
  35415. */
  35416. function PBRBaseMaterial(name, scene) {
  35417. var _this = _super.call(this, name, scene) || this;
  35418. /**
  35419. * Intensity of the direct lights e.g. the four lights available in your scene.
  35420. * This impacts both the direct diffuse and specular highlights.
  35421. */
  35422. _this._directIntensity = 1.0;
  35423. /**
  35424. * Intensity of the emissive part of the material.
  35425. * This helps controlling the emissive effect without modifying the emissive color.
  35426. */
  35427. _this._emissiveIntensity = 1.0;
  35428. /**
  35429. * Intensity of the environment e.g. how much the environment will light the object
  35430. * either through harmonics for rough material or through the refelction for shiny ones.
  35431. */
  35432. _this._environmentIntensity = 1.0;
  35433. /**
  35434. * This is a special control allowing the reduction of the specular highlights coming from the
  35435. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  35436. */
  35437. _this._specularIntensity = 1.0;
  35438. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  35439. /**
  35440. * Debug Control allowing disabling the bump map on this material.
  35441. */
  35442. _this._disableBumpMap = false;
  35443. /**
  35444. * AKA Occlusion Texture Intensity in other nomenclature.
  35445. */
  35446. _this._ambientTextureStrength = 1.0;
  35447. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  35448. /**
  35449. * AKA Diffuse Color in other nomenclature.
  35450. */
  35451. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  35452. /**
  35453. * AKA Specular Color in other nomenclature.
  35454. */
  35455. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  35456. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  35457. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  35458. /**
  35459. * AKA Glossiness in other nomenclature.
  35460. */
  35461. _this._microSurface = 0.9;
  35462. /**
  35463. * source material index of refraction (IOR)' / 'destination material IOR.
  35464. */
  35465. _this._indexOfRefraction = 0.66;
  35466. /**
  35467. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  35468. */
  35469. _this._invertRefractionY = false;
  35470. /**
  35471. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  35472. * Materials half opaque for instance using refraction could benefit from this control.
  35473. */
  35474. _this._linkRefractionWithTransparency = false;
  35475. _this._useLightmapAsShadowmap = false;
  35476. /**
  35477. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  35478. * makes the reflect vector face the model (under horizon).
  35479. */
  35480. _this._useHorizonOcclusion = false; // USEHORIZONOCCLUSION
  35481. /**
  35482. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  35483. * too much the area relying on ambient texture to define their ambient occlusion.
  35484. */
  35485. _this._useRadianceOcclusion = false;
  35486. /**
  35487. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  35488. */
  35489. _this._useAlphaFromAlbedoTexture = false;
  35490. /**
  35491. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  35492. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  35493. */
  35494. _this._useSpecularOverAlpha = true;
  35495. /**
  35496. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  35497. */
  35498. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  35499. /**
  35500. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  35501. */
  35502. _this._useRoughnessFromMetallicTextureAlpha = true;
  35503. /**
  35504. * Specifies if the metallic texture contains the roughness information in its green channel.
  35505. */
  35506. _this._useRoughnessFromMetallicTextureGreen = false;
  35507. /**
  35508. * Specifies if the metallic texture contains the metallness information in its blue channel.
  35509. */
  35510. _this._useMetallnessFromMetallicTextureBlue = false;
  35511. /**
  35512. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  35513. */
  35514. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  35515. /**
  35516. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  35517. */
  35518. _this._useAmbientInGrayScale = false;
  35519. /**
  35520. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  35521. * The material will try to infer what glossiness each pixel should be.
  35522. */
  35523. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  35524. /**
  35525. * BJS is using an harcoded light falloff based on a manually sets up range.
  35526. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  35527. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  35528. */
  35529. _this._usePhysicalLightFalloff = true;
  35530. /**
  35531. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  35532. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  35533. */
  35534. _this._useRadianceOverAlpha = true;
  35535. /**
  35536. * Allows using the bump map in parallax mode.
  35537. */
  35538. _this._useParallax = false;
  35539. /**
  35540. * Allows using the bump map in parallax occlusion mode.
  35541. */
  35542. _this._useParallaxOcclusion = false;
  35543. /**
  35544. * Controls the scale bias of the parallax mode.
  35545. */
  35546. _this._parallaxScaleBias = 0.05;
  35547. /**
  35548. * If sets to true, disables all the lights affecting the material.
  35549. */
  35550. _this._disableLighting = false;
  35551. /**
  35552. * Number of Simultaneous lights allowed on the material.
  35553. */
  35554. _this._maxSimultaneousLights = 4;
  35555. /**
  35556. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  35557. */
  35558. _this._invertNormalMapX = false;
  35559. /**
  35560. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  35561. */
  35562. _this._invertNormalMapY = false;
  35563. /**
  35564. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35565. */
  35566. _this._twoSidedLighting = false;
  35567. /**
  35568. * Defines the alpha limits in alpha test mode.
  35569. */
  35570. _this._alphaCutOff = 0.4;
  35571. /**
  35572. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  35573. */
  35574. _this._forceAlphaTest = false;
  35575. /**
  35576. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  35577. * And/Or occlude the blended part.
  35578. */
  35579. _this._useAlphaFresnel = false;
  35580. /**
  35581. * The transparency mode of the material.
  35582. */
  35583. _this._transparencyMode = null;
  35584. /**
  35585. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  35586. * from cos thetav and roughness:
  35587. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  35588. */
  35589. _this._environmentBRDFTexture = null;
  35590. /**
  35591. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  35592. */
  35593. _this._forceIrradianceInFragment = false;
  35594. /**
  35595. * Force normal to face away from face.
  35596. * (Temporary internal fix to remove before 3.1)
  35597. */
  35598. _this._forceNormalForward = false;
  35599. _this._renderTargets = new BABYLON.SmartArray(16);
  35600. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  35601. // Setup the default processing configuration to the scene.
  35602. _this._attachImageProcessingConfiguration(null);
  35603. _this.getRenderTargetTextures = function () {
  35604. _this._renderTargets.reset();
  35605. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  35606. _this._renderTargets.push(_this._reflectionTexture);
  35607. }
  35608. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  35609. _this._renderTargets.push(_this._refractionTexture);
  35610. }
  35611. return _this._renderTargets;
  35612. };
  35613. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  35614. return _this;
  35615. }
  35616. /**
  35617. * Attaches a new image processing configuration to the PBR Material.
  35618. * @param configuration
  35619. */
  35620. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  35621. var _this = this;
  35622. if (configuration === this._imageProcessingConfiguration) {
  35623. return;
  35624. }
  35625. // Detaches observer.
  35626. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35627. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35628. }
  35629. // Pick the scene configuration if needed.
  35630. if (!configuration) {
  35631. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  35632. }
  35633. else {
  35634. this._imageProcessingConfiguration = configuration;
  35635. }
  35636. // Attaches observer.
  35637. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  35638. _this._markAllSubMeshesAsImageProcessingDirty();
  35639. });
  35640. };
  35641. PBRBaseMaterial.prototype.getClassName = function () {
  35642. return "PBRBaseMaterial";
  35643. };
  35644. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  35645. get: function () {
  35646. return this._useLogarithmicDepth;
  35647. },
  35648. set: function (value) {
  35649. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  35650. },
  35651. enumerable: true,
  35652. configurable: true
  35653. });
  35654. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  35655. /**
  35656. * Gets the current transparency mode.
  35657. */
  35658. get: function () {
  35659. return this._transparencyMode;
  35660. },
  35661. /**
  35662. * Sets the transparency mode of the material.
  35663. */
  35664. set: function (value) {
  35665. if (this._transparencyMode === value) {
  35666. return;
  35667. }
  35668. this._transparencyMode = value;
  35669. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  35670. this._markAllSubMeshesAsTexturesDirty();
  35671. },
  35672. enumerable: true,
  35673. configurable: true
  35674. });
  35675. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  35676. /**
  35677. * Returns true if alpha blending should be disabled.
  35678. */
  35679. get: function () {
  35680. return (this._linkRefractionWithTransparency ||
  35681. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  35682. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  35683. },
  35684. enumerable: true,
  35685. configurable: true
  35686. });
  35687. /**
  35688. * Specifies whether or not this material should be rendered in alpha blend mode.
  35689. */
  35690. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  35691. if (this._disableAlphaBlending) {
  35692. return false;
  35693. }
  35694. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  35695. };
  35696. /**
  35697. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  35698. */
  35699. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  35700. if (this._disableAlphaBlending) {
  35701. return false;
  35702. }
  35703. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  35704. };
  35705. /**
  35706. * Specifies whether or not this material should be rendered in alpha test mode.
  35707. */
  35708. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  35709. if (this._forceAlphaTest) {
  35710. return true;
  35711. }
  35712. if (this._linkRefractionWithTransparency) {
  35713. return false;
  35714. }
  35715. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  35716. };
  35717. /**
  35718. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  35719. */
  35720. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  35721. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35722. };
  35723. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  35724. return this._albedoTexture;
  35725. };
  35726. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35727. var _this = this;
  35728. if (subMesh.effect && this.isFrozen) {
  35729. if (this._wasPreviouslyReady) {
  35730. return true;
  35731. }
  35732. }
  35733. if (!subMesh._materialDefines) {
  35734. subMesh._materialDefines = new PBRMaterialDefines();
  35735. }
  35736. var scene = this.getScene();
  35737. var defines = subMesh._materialDefines;
  35738. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  35739. if (defines._renderId === scene.getRenderId()) {
  35740. return true;
  35741. }
  35742. }
  35743. var engine = scene.getEngine();
  35744. // Lights
  35745. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  35746. defines._needNormals = true;
  35747. // Textures
  35748. if (defines._areTexturesDirty) {
  35749. defines._needUVs = false;
  35750. if (scene.texturesEnabled) {
  35751. if (scene.getEngine().getCaps().textureLOD) {
  35752. defines.LODBASEDMICROSFURACE = true;
  35753. }
  35754. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35755. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  35756. return false;
  35757. }
  35758. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  35759. }
  35760. else {
  35761. defines.ALBEDO = false;
  35762. }
  35763. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35764. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  35765. return false;
  35766. }
  35767. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  35768. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  35769. }
  35770. else {
  35771. defines.AMBIENT = false;
  35772. }
  35773. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35774. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  35775. return false;
  35776. }
  35777. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  35778. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  35779. }
  35780. else {
  35781. defines.OPACITY = false;
  35782. }
  35783. var reflectionTexture = this._getReflectionTexture();
  35784. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35785. if (!reflectionTexture.isReadyOrNotBlocking()) {
  35786. return false;
  35787. }
  35788. defines.REFLECTION = true;
  35789. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  35790. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  35791. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  35792. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  35793. defines.INVERTCUBICMAP = true;
  35794. }
  35795. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  35796. switch (reflectionTexture.coordinatesMode) {
  35797. case BABYLON.Texture.CUBIC_MODE:
  35798. case BABYLON.Texture.INVCUBIC_MODE:
  35799. defines.REFLECTIONMAP_CUBIC = true;
  35800. break;
  35801. case BABYLON.Texture.EXPLICIT_MODE:
  35802. defines.REFLECTIONMAP_EXPLICIT = true;
  35803. break;
  35804. case BABYLON.Texture.PLANAR_MODE:
  35805. defines.REFLECTIONMAP_PLANAR = true;
  35806. break;
  35807. case BABYLON.Texture.PROJECTION_MODE:
  35808. defines.REFLECTIONMAP_PROJECTION = true;
  35809. break;
  35810. case BABYLON.Texture.SKYBOX_MODE:
  35811. defines.REFLECTIONMAP_SKYBOX = true;
  35812. break;
  35813. case BABYLON.Texture.SPHERICAL_MODE:
  35814. defines.REFLECTIONMAP_SPHERICAL = true;
  35815. break;
  35816. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35817. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  35818. break;
  35819. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35820. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  35821. break;
  35822. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35823. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  35824. break;
  35825. }
  35826. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  35827. if (reflectionTexture.sphericalPolynomial) {
  35828. defines.USESPHERICALFROMREFLECTIONMAP = true;
  35829. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  35830. defines.USESPHERICALINVERTEX = false;
  35831. }
  35832. else {
  35833. defines.USESPHERICALINVERTEX = true;
  35834. }
  35835. }
  35836. }
  35837. }
  35838. else {
  35839. defines.REFLECTION = false;
  35840. defines.REFLECTIONMAP_3D = false;
  35841. defines.REFLECTIONMAP_SPHERICAL = false;
  35842. defines.REFLECTIONMAP_PLANAR = false;
  35843. defines.REFLECTIONMAP_CUBIC = false;
  35844. defines.REFLECTIONMAP_PROJECTION = false;
  35845. defines.REFLECTIONMAP_SKYBOX = false;
  35846. defines.REFLECTIONMAP_EXPLICIT = false;
  35847. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35848. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35849. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35850. defines.INVERTCUBICMAP = false;
  35851. defines.USESPHERICALFROMREFLECTIONMAP = false;
  35852. defines.USESPHERICALINVERTEX = false;
  35853. defines.REFLECTIONMAP_OPPOSITEZ = false;
  35854. defines.LODINREFLECTIONALPHA = false;
  35855. defines.GAMMAREFLECTION = false;
  35856. }
  35857. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35858. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  35859. return false;
  35860. }
  35861. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  35862. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35863. }
  35864. else {
  35865. defines.LIGHTMAP = false;
  35866. }
  35867. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35868. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  35869. return false;
  35870. }
  35871. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  35872. }
  35873. else {
  35874. defines.EMISSIVE = false;
  35875. }
  35876. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35877. if (this._metallicTexture) {
  35878. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  35879. return false;
  35880. }
  35881. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  35882. defines.METALLICWORKFLOW = true;
  35883. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  35884. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  35885. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  35886. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  35887. }
  35888. else if (this._reflectivityTexture) {
  35889. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  35890. return false;
  35891. }
  35892. defines.METALLICWORKFLOW = false;
  35893. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  35894. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  35895. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  35896. }
  35897. else {
  35898. defines.METALLICWORKFLOW = false;
  35899. defines.REFLECTIVITY = false;
  35900. }
  35901. if (this._microSurfaceTexture) {
  35902. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  35903. return false;
  35904. }
  35905. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  35906. }
  35907. else {
  35908. defines.MICROSURFACEMAP = false;
  35909. }
  35910. }
  35911. else {
  35912. defines.REFLECTIVITY = false;
  35913. defines.MICROSURFACEMAP = false;
  35914. }
  35915. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35916. // Bump texure can not be none blocking.
  35917. if (!this._bumpTexture.isReady()) {
  35918. return false;
  35919. }
  35920. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  35921. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35922. defines.PARALLAX = true;
  35923. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  35924. }
  35925. else {
  35926. defines.PARALLAX = false;
  35927. }
  35928. }
  35929. else {
  35930. defines.BUMP = false;
  35931. }
  35932. var refractionTexture = this._getRefractionTexture();
  35933. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35934. if (!refractionTexture.isReadyOrNotBlocking()) {
  35935. return false;
  35936. }
  35937. defines.REFRACTION = true;
  35938. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  35939. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  35940. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  35941. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  35942. if (this._linkRefractionWithTransparency) {
  35943. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  35944. }
  35945. }
  35946. else {
  35947. defines.REFRACTION = false;
  35948. }
  35949. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35950. // This is blocking.
  35951. if (!this._environmentBRDFTexture.isReady()) {
  35952. return false;
  35953. }
  35954. defines.ENVIRONMENTBRDF = true;
  35955. }
  35956. else {
  35957. defines.ENVIRONMENTBRDF = false;
  35958. }
  35959. if (this._shouldUseAlphaFromAlbedoTexture()) {
  35960. defines.ALPHAFROMALBEDO = true;
  35961. }
  35962. else {
  35963. defines.ALPHAFROMALBEDO = false;
  35964. }
  35965. }
  35966. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  35967. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  35968. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  35969. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  35970. defines.METALLICWORKFLOW = true;
  35971. }
  35972. else {
  35973. defines.METALLICWORKFLOW = false;
  35974. }
  35975. if (!this.backFaceCulling && this._twoSidedLighting) {
  35976. defines.TWOSIDEDLIGHTING = true;
  35977. }
  35978. else {
  35979. defines.TWOSIDEDLIGHTING = false;
  35980. }
  35981. defines.ALPHATESTVALUE = this._alphaCutOff;
  35982. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  35983. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  35984. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  35985. }
  35986. if (defines._areImageProcessingDirty) {
  35987. if (!this._imageProcessingConfiguration.isReady()) {
  35988. return false;
  35989. }
  35990. this._imageProcessingConfiguration.prepareDefines(defines);
  35991. }
  35992. defines.FORCENORMALFORWARD = this._forceNormalForward;
  35993. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  35994. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  35995. // Misc.
  35996. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35997. // Values that need to be evaluated on every frame
  35998. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._forceAlphaTest);
  35999. // Attribs
  36000. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE)) {
  36001. if (mesh) {
  36002. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36003. mesh.createNormals(true);
  36004. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  36005. }
  36006. }
  36007. }
  36008. // Get correct effect
  36009. if (defines.isDirty) {
  36010. defines.markAsProcessed();
  36011. scene.resetCachedMaterial();
  36012. // Fallbacks
  36013. var fallbacks = new BABYLON.EffectFallbacks();
  36014. var fallbackRank = 0;
  36015. if (defines.USESPHERICALINVERTEX) {
  36016. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  36017. }
  36018. if (defines.FOG) {
  36019. fallbacks.addFallback(fallbackRank, "FOG");
  36020. }
  36021. if (defines.POINTSIZE) {
  36022. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  36023. }
  36024. if (defines.LOGARITHMICDEPTH) {
  36025. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  36026. }
  36027. if (defines.PARALLAX) {
  36028. fallbacks.addFallback(fallbackRank, "PARALLAX");
  36029. }
  36030. if (defines.PARALLAXOCCLUSION) {
  36031. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  36032. }
  36033. if (defines.ENVIRONMENTBRDF) {
  36034. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  36035. }
  36036. if (defines.TANGENT) {
  36037. fallbacks.addFallback(fallbackRank++, "TANGENT");
  36038. }
  36039. if (defines.BUMP) {
  36040. fallbacks.addFallback(fallbackRank++, "BUMP");
  36041. }
  36042. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  36043. if (defines.SPECULARTERM) {
  36044. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  36045. }
  36046. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  36047. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  36048. }
  36049. if (defines.LIGHTMAP) {
  36050. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  36051. }
  36052. if (defines.NORMAL) {
  36053. fallbacks.addFallback(fallbackRank++, "NORMAL");
  36054. }
  36055. if (defines.AMBIENT) {
  36056. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  36057. }
  36058. if (defines.EMISSIVE) {
  36059. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  36060. }
  36061. if (defines.VERTEXCOLOR) {
  36062. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  36063. }
  36064. if (defines.NUM_BONE_INFLUENCERS > 0) {
  36065. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  36066. }
  36067. if (defines.MORPHTARGETS) {
  36068. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  36069. }
  36070. //Attributes
  36071. var attribs = [BABYLON.VertexBuffer.PositionKind];
  36072. if (defines.NORMAL) {
  36073. attribs.push(BABYLON.VertexBuffer.NormalKind);
  36074. }
  36075. if (defines.TANGENT) {
  36076. attribs.push(BABYLON.VertexBuffer.TangentKind);
  36077. }
  36078. if (defines.UV1) {
  36079. attribs.push(BABYLON.VertexBuffer.UVKind);
  36080. }
  36081. if (defines.UV2) {
  36082. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  36083. }
  36084. if (defines.VERTEXCOLOR) {
  36085. attribs.push(BABYLON.VertexBuffer.ColorKind);
  36086. }
  36087. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  36088. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  36089. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  36090. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  36091. "vFogInfos", "vFogColor", "pointSize",
  36092. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  36093. "mBones",
  36094. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  36095. "vLightingIntensity",
  36096. "logarithmicDepthConstant",
  36097. "vSphericalX", "vSphericalY", "vSphericalZ",
  36098. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  36099. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  36100. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  36101. "vTangentSpaceParams"
  36102. ];
  36103. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  36104. "bumpSampler", "lightmapSampler", "opacitySampler",
  36105. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  36106. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  36107. "microSurfaceSampler", "environmentBrdfSampler"];
  36108. var uniformBuffers = ["Material", "Scene"];
  36109. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  36110. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  36111. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  36112. uniformsNames: uniforms,
  36113. uniformBuffersNames: uniformBuffers,
  36114. samplers: samplers,
  36115. defines: defines,
  36116. maxSimultaneousLights: this._maxSimultaneousLights
  36117. });
  36118. var onCompiled = function (effect) {
  36119. if (_this.onCompiled) {
  36120. _this.onCompiled(effect);
  36121. }
  36122. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  36123. };
  36124. var join = defines.toString();
  36125. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  36126. attributes: attribs,
  36127. uniformsNames: uniforms,
  36128. uniformBuffersNames: uniformBuffers,
  36129. samplers: samplers,
  36130. defines: join,
  36131. fallbacks: fallbacks,
  36132. onCompiled: onCompiled,
  36133. onError: this.onError,
  36134. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  36135. }, engine), defines);
  36136. this.buildUniformLayout();
  36137. }
  36138. if (!subMesh.effect || !subMesh.effect.isReady()) {
  36139. return false;
  36140. }
  36141. defines._renderId = scene.getRenderId();
  36142. this._wasPreviouslyReady = true;
  36143. return true;
  36144. };
  36145. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  36146. // Order is important !
  36147. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  36148. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  36149. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  36150. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  36151. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  36152. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  36153. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  36154. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  36155. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  36156. this._uniformBuffer.addUniform("vBumpInfos", 3);
  36157. this._uniformBuffer.addUniform("albedoMatrix", 16);
  36158. this._uniformBuffer.addUniform("ambientMatrix", 16);
  36159. this._uniformBuffer.addUniform("opacityMatrix", 16);
  36160. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  36161. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  36162. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  36163. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  36164. this._uniformBuffer.addUniform("bumpMatrix", 16);
  36165. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  36166. this._uniformBuffer.addUniform("refractionMatrix", 16);
  36167. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  36168. this._uniformBuffer.addUniform("vReflectionColor", 3);
  36169. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  36170. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  36171. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  36172. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  36173. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  36174. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  36175. this._uniformBuffer.addUniform("pointSize", 1);
  36176. this._uniformBuffer.create();
  36177. };
  36178. PBRBaseMaterial.prototype.unbind = function () {
  36179. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  36180. this._uniformBuffer.setTexture("reflectionSampler", null);
  36181. }
  36182. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  36183. this._uniformBuffer.setTexture("refractionSampler", null);
  36184. }
  36185. _super.prototype.unbind.call(this);
  36186. };
  36187. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  36188. this._activeEffect.setMatrix("world", world);
  36189. };
  36190. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  36191. var scene = this.getScene();
  36192. var defines = subMesh._materialDefines;
  36193. if (!defines) {
  36194. return;
  36195. }
  36196. var effect = subMesh.effect;
  36197. if (!effect) {
  36198. return;
  36199. }
  36200. this._activeEffect = effect;
  36201. // Matrices
  36202. this.bindOnlyWorldMatrix(world);
  36203. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  36204. // Bones
  36205. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  36206. var reflectionTexture = null;
  36207. if (mustRebind) {
  36208. this._uniformBuffer.bindToEffect(effect, "Material");
  36209. this.bindViewProjection(effect);
  36210. reflectionTexture = this._getReflectionTexture();
  36211. var refractionTexture = this._getRefractionTexture();
  36212. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  36213. // Texture uniforms
  36214. if (scene.texturesEnabled) {
  36215. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36216. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  36217. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  36218. }
  36219. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36220. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  36221. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  36222. }
  36223. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36224. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  36225. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  36226. }
  36227. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36228. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  36229. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  36230. var polynomials = reflectionTexture.sphericalPolynomial;
  36231. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  36232. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  36233. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  36234. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  36235. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  36236. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  36237. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  36238. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  36239. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  36240. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  36241. }
  36242. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  36243. }
  36244. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  36245. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  36246. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  36247. }
  36248. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  36249. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  36250. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  36251. }
  36252. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  36253. if (this._metallicTexture) {
  36254. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  36255. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  36256. }
  36257. else if (this._reflectivityTexture) {
  36258. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  36259. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  36260. }
  36261. if (this._microSurfaceTexture) {
  36262. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  36263. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  36264. }
  36265. }
  36266. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  36267. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  36268. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  36269. if (scene._mirroredCameraPosition) {
  36270. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  36271. }
  36272. else {
  36273. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  36274. }
  36275. }
  36276. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  36277. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  36278. var depth = 1.0;
  36279. if (!refractionTexture.isCube) {
  36280. if (refractionTexture.depth) {
  36281. depth = refractionTexture.depth;
  36282. }
  36283. }
  36284. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  36285. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  36286. }
  36287. }
  36288. // Point size
  36289. if (this.pointsCloud) {
  36290. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  36291. }
  36292. // Colors
  36293. if (defines.METALLICWORKFLOW) {
  36294. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  36295. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  36296. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  36297. }
  36298. else {
  36299. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  36300. }
  36301. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  36302. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  36303. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  36304. // Misc
  36305. this._lightingInfos.x = this._directIntensity;
  36306. this._lightingInfos.y = this._emissiveIntensity;
  36307. this._lightingInfos.z = this._environmentIntensity;
  36308. this._lightingInfos.w = this._specularIntensity;
  36309. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  36310. }
  36311. // Textures
  36312. if (scene.texturesEnabled) {
  36313. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36314. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  36315. }
  36316. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36317. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  36318. }
  36319. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36320. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  36321. }
  36322. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36323. if (defines.LODBASEDMICROSFURACE) {
  36324. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  36325. }
  36326. else {
  36327. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  36328. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  36329. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  36330. }
  36331. }
  36332. if (defines.ENVIRONMENTBRDF) {
  36333. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  36334. }
  36335. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  36336. if (defines.LODBASEDMICROSFURACE) {
  36337. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  36338. }
  36339. else {
  36340. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  36341. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  36342. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  36343. }
  36344. }
  36345. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  36346. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  36347. }
  36348. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  36349. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  36350. }
  36351. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  36352. if (this._metallicTexture) {
  36353. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  36354. }
  36355. else if (this._reflectivityTexture) {
  36356. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  36357. }
  36358. if (this._microSurfaceTexture) {
  36359. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  36360. }
  36361. }
  36362. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  36363. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  36364. }
  36365. }
  36366. // Clip plane
  36367. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  36368. // Colors
  36369. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  36370. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  36371. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  36372. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  36373. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  36374. }
  36375. if (mustRebind || !this.isFrozen) {
  36376. // Lights
  36377. if (scene.lightsEnabled && !this._disableLighting) {
  36378. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  36379. }
  36380. // View
  36381. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  36382. this.bindView(effect);
  36383. }
  36384. // Fog
  36385. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  36386. // Morph targets
  36387. if (defines.NUM_MORPH_INFLUENCERS) {
  36388. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  36389. }
  36390. // image processing
  36391. this._imageProcessingConfiguration.bind(this._activeEffect);
  36392. // Log. depth
  36393. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  36394. }
  36395. this._uniformBuffer.update();
  36396. this._afterBind(mesh);
  36397. };
  36398. PBRBaseMaterial.prototype.getAnimatables = function () {
  36399. var results = [];
  36400. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  36401. results.push(this._albedoTexture);
  36402. }
  36403. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  36404. results.push(this._ambientTexture);
  36405. }
  36406. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  36407. results.push(this._opacityTexture);
  36408. }
  36409. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  36410. results.push(this._reflectionTexture);
  36411. }
  36412. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  36413. results.push(this._emissiveTexture);
  36414. }
  36415. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  36416. results.push(this._metallicTexture);
  36417. }
  36418. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  36419. results.push(this._reflectivityTexture);
  36420. }
  36421. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  36422. results.push(this._bumpTexture);
  36423. }
  36424. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  36425. results.push(this._lightmapTexture);
  36426. }
  36427. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  36428. results.push(this._refractionTexture);
  36429. }
  36430. return results;
  36431. };
  36432. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  36433. if (this._reflectionTexture) {
  36434. return this._reflectionTexture;
  36435. }
  36436. return this.getScene().environmentTexture;
  36437. };
  36438. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  36439. if (this._refractionTexture) {
  36440. return this._refractionTexture;
  36441. }
  36442. if (this._linkRefractionWithTransparency) {
  36443. return this.getScene().environmentTexture;
  36444. }
  36445. return null;
  36446. };
  36447. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36448. if (forceDisposeTextures) {
  36449. if (this._albedoTexture) {
  36450. this._albedoTexture.dispose();
  36451. }
  36452. if (this._ambientTexture) {
  36453. this._ambientTexture.dispose();
  36454. }
  36455. if (this._opacityTexture) {
  36456. this._opacityTexture.dispose();
  36457. }
  36458. if (this._reflectionTexture) {
  36459. this._reflectionTexture.dispose();
  36460. }
  36461. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  36462. this._environmentBRDFTexture.dispose();
  36463. }
  36464. if (this._emissiveTexture) {
  36465. this._emissiveTexture.dispose();
  36466. }
  36467. if (this._metallicTexture) {
  36468. this._metallicTexture.dispose();
  36469. }
  36470. if (this._reflectivityTexture) {
  36471. this._reflectivityTexture.dispose();
  36472. }
  36473. if (this._bumpTexture) {
  36474. this._bumpTexture.dispose();
  36475. }
  36476. if (this._lightmapTexture) {
  36477. this._lightmapTexture.dispose();
  36478. }
  36479. if (this._refractionTexture) {
  36480. this._refractionTexture.dispose();
  36481. }
  36482. }
  36483. this._renderTargets.dispose();
  36484. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36485. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36486. }
  36487. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  36488. };
  36489. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  36490. __decorate([
  36491. BABYLON.serializeAsImageProcessingConfiguration()
  36492. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  36493. __decorate([
  36494. BABYLON.serialize()
  36495. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  36496. __decorate([
  36497. BABYLON.serialize()
  36498. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  36499. return PBRBaseMaterial;
  36500. }(BABYLON.PushMaterial));
  36501. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  36502. })(BABYLON || (BABYLON = {}));
  36503. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  36504. var BABYLON;
  36505. (function (BABYLON) {
  36506. var Internals;
  36507. (function (Internals) {
  36508. /**
  36509. * The Physically based simple base material of BJS.
  36510. *
  36511. * This enables better naming and convention enforcements on top of the pbrMaterial.
  36512. * It is used as the base class for both the specGloss and metalRough conventions.
  36513. */
  36514. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  36515. __extends(PBRBaseSimpleMaterial, _super);
  36516. /**
  36517. * Instantiates a new PBRMaterial instance.
  36518. *
  36519. * @param name The material name
  36520. * @param scene The scene the material will be use in.
  36521. */
  36522. function PBRBaseSimpleMaterial(name, scene) {
  36523. var _this = _super.call(this, name, scene) || this;
  36524. /**
  36525. * Number of Simultaneous lights allowed on the material.
  36526. */
  36527. _this.maxSimultaneousLights = 4;
  36528. /**
  36529. * If sets to true, disables all the lights affecting the material.
  36530. */
  36531. _this.disableLighting = false;
  36532. /**
  36533. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36534. */
  36535. _this.invertNormalMapX = false;
  36536. /**
  36537. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36538. */
  36539. _this.invertNormalMapY = false;
  36540. /**
  36541. * Emissivie color used to self-illuminate the model.
  36542. */
  36543. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36544. /**
  36545. * Occlusion Channel Strenght.
  36546. */
  36547. _this.occlusionStrength = 1.0;
  36548. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  36549. _this._useAlphaFromAlbedoTexture = true;
  36550. _this._useAmbientInGrayScale = true;
  36551. return _this;
  36552. }
  36553. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  36554. /**
  36555. * Gets the current double sided mode.
  36556. */
  36557. get: function () {
  36558. return this._twoSidedLighting;
  36559. },
  36560. /**
  36561. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36562. */
  36563. set: function (value) {
  36564. if (this._twoSidedLighting === value) {
  36565. return;
  36566. }
  36567. this._twoSidedLighting = value;
  36568. this.backFaceCulling = !value;
  36569. this._markAllSubMeshesAsTexturesDirty();
  36570. },
  36571. enumerable: true,
  36572. configurable: true
  36573. });
  36574. /**
  36575. * Return the active textures of the material.
  36576. */
  36577. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  36578. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36579. if (this.environmentTexture) {
  36580. activeTextures.push(this.environmentTexture);
  36581. }
  36582. if (this.normalTexture) {
  36583. activeTextures.push(this.normalTexture);
  36584. }
  36585. if (this.emissiveTexture) {
  36586. activeTextures.push(this.emissiveTexture);
  36587. }
  36588. if (this.occlusionTexture) {
  36589. activeTextures.push(this.occlusionTexture);
  36590. }
  36591. return activeTextures;
  36592. };
  36593. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  36594. return "PBRBaseSimpleMaterial";
  36595. };
  36596. __decorate([
  36597. BABYLON.serialize(),
  36598. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36599. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  36600. __decorate([
  36601. BABYLON.serialize(),
  36602. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36603. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  36604. __decorate([
  36605. BABYLON.serializeAsTexture(),
  36606. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  36607. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  36608. __decorate([
  36609. BABYLON.serialize(),
  36610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36611. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  36612. __decorate([
  36613. BABYLON.serialize(),
  36614. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36615. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  36616. __decorate([
  36617. BABYLON.serializeAsTexture(),
  36618. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  36619. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  36620. __decorate([
  36621. BABYLON.serializeAsColor3("emissive"),
  36622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36623. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  36624. __decorate([
  36625. BABYLON.serializeAsTexture(),
  36626. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36627. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  36628. __decorate([
  36629. BABYLON.serialize(),
  36630. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  36631. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  36632. __decorate([
  36633. BABYLON.serializeAsTexture(),
  36634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  36635. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  36636. __decorate([
  36637. BABYLON.serialize(),
  36638. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  36639. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  36640. __decorate([
  36641. BABYLON.serialize()
  36642. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  36643. return PBRBaseSimpleMaterial;
  36644. }(BABYLON.PBRBaseMaterial));
  36645. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  36646. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  36647. })(BABYLON || (BABYLON = {}));
  36648. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  36649. var BABYLON;
  36650. (function (BABYLON) {
  36651. /**
  36652. * The Physically based material of BJS.
  36653. *
  36654. * This offers the main features of a standard PBR material.
  36655. * For more information, please refer to the documentation :
  36656. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  36657. */
  36658. var PBRMaterial = /** @class */ (function (_super) {
  36659. __extends(PBRMaterial, _super);
  36660. /**
  36661. * Instantiates a new PBRMaterial instance.
  36662. *
  36663. * @param name The material name
  36664. * @param scene The scene the material will be use in.
  36665. */
  36666. function PBRMaterial(name, scene) {
  36667. var _this = _super.call(this, name, scene) || this;
  36668. /**
  36669. * Intensity of the direct lights e.g. the four lights available in your scene.
  36670. * This impacts both the direct diffuse and specular highlights.
  36671. */
  36672. _this.directIntensity = 1.0;
  36673. /**
  36674. * Intensity of the emissive part of the material.
  36675. * This helps controlling the emissive effect without modifying the emissive color.
  36676. */
  36677. _this.emissiveIntensity = 1.0;
  36678. /**
  36679. * Intensity of the environment e.g. how much the environment will light the object
  36680. * either through harmonics for rough material or through the refelction for shiny ones.
  36681. */
  36682. _this.environmentIntensity = 1.0;
  36683. /**
  36684. * This is a special control allowing the reduction of the specular highlights coming from the
  36685. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  36686. */
  36687. _this.specularIntensity = 1.0;
  36688. /**
  36689. * Debug Control allowing disabling the bump map on this material.
  36690. */
  36691. _this.disableBumpMap = false;
  36692. /**
  36693. * AKA Occlusion Texture Intensity in other nomenclature.
  36694. */
  36695. _this.ambientTextureStrength = 1.0;
  36696. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  36697. /**
  36698. * AKA Diffuse Color in other nomenclature.
  36699. */
  36700. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  36701. /**
  36702. * AKA Specular Color in other nomenclature.
  36703. */
  36704. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  36705. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  36706. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36707. /**
  36708. * AKA Glossiness in other nomenclature.
  36709. */
  36710. _this.microSurface = 1.0;
  36711. /**
  36712. * source material index of refraction (IOR)' / 'destination material IOR.
  36713. */
  36714. _this.indexOfRefraction = 0.66;
  36715. /**
  36716. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  36717. */
  36718. _this.invertRefractionY = false;
  36719. /**
  36720. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  36721. * Materials half opaque for instance using refraction could benefit from this control.
  36722. */
  36723. _this.linkRefractionWithTransparency = false;
  36724. _this.useLightmapAsShadowmap = false;
  36725. /**
  36726. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  36727. */
  36728. _this.useAlphaFromAlbedoTexture = false;
  36729. /**
  36730. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  36731. */
  36732. _this.forceAlphaTest = false;
  36733. /**
  36734. * Defines the alpha limits in alpha test mode.
  36735. */
  36736. _this.alphaCutOff = 0.4;
  36737. /**
  36738. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  36739. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  36740. */
  36741. _this.useSpecularOverAlpha = true;
  36742. /**
  36743. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  36744. */
  36745. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  36746. /**
  36747. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  36748. */
  36749. _this.useRoughnessFromMetallicTextureAlpha = true;
  36750. /**
  36751. * Specifies if the metallic texture contains the roughness information in its green channel.
  36752. */
  36753. _this.useRoughnessFromMetallicTextureGreen = false;
  36754. /**
  36755. * Specifies if the metallic texture contains the metallness information in its blue channel.
  36756. */
  36757. _this.useMetallnessFromMetallicTextureBlue = false;
  36758. /**
  36759. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  36760. */
  36761. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  36762. /**
  36763. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  36764. */
  36765. _this.useAmbientInGrayScale = false;
  36766. /**
  36767. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  36768. * The material will try to infer what glossiness each pixel should be.
  36769. */
  36770. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  36771. /**
  36772. * BJS is using an harcoded light falloff based on a manually sets up range.
  36773. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  36774. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  36775. */
  36776. _this.usePhysicalLightFalloff = true;
  36777. /**
  36778. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  36779. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  36780. */
  36781. _this.useRadianceOverAlpha = true;
  36782. /**
  36783. * Allows using the bump map in parallax mode.
  36784. */
  36785. _this.useParallax = false;
  36786. /**
  36787. * Allows using the bump map in parallax occlusion mode.
  36788. */
  36789. _this.useParallaxOcclusion = false;
  36790. /**
  36791. * Controls the scale bias of the parallax mode.
  36792. */
  36793. _this.parallaxScaleBias = 0.05;
  36794. /**
  36795. * If sets to true, disables all the lights affecting the material.
  36796. */
  36797. _this.disableLighting = false;
  36798. /**
  36799. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  36800. */
  36801. _this.forceIrradianceInFragment = false;
  36802. /**
  36803. * Number of Simultaneous lights allowed on the material.
  36804. */
  36805. _this.maxSimultaneousLights = 4;
  36806. /**
  36807. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36808. */
  36809. _this.invertNormalMapX = false;
  36810. /**
  36811. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36812. */
  36813. _this.invertNormalMapY = false;
  36814. /**
  36815. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36816. */
  36817. _this.twoSidedLighting = false;
  36818. /**
  36819. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36820. * And/Or occlude the blended part.
  36821. */
  36822. _this.useAlphaFresnel = false;
  36823. /**
  36824. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36825. * And/Or occlude the blended part.
  36826. */
  36827. _this.environmentBRDFTexture = null;
  36828. /**
  36829. * Force normal to face away from face.
  36830. * (Temporary internal fix to remove before 3.1)
  36831. */
  36832. _this.forceNormalForward = false;
  36833. /**
  36834. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  36835. * makes the reflect vector face the model (under horizon).
  36836. */
  36837. _this.useHorizonOcclusion = false;
  36838. /**
  36839. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  36840. * too much the area relying on ambient texture to define their ambient occlusion.
  36841. */
  36842. _this.useRadianceOcclusion = false;
  36843. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  36844. return _this;
  36845. }
  36846. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  36847. /**
  36848. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  36849. */
  36850. get: function () {
  36851. return this._PBRMATERIAL_OPAQUE;
  36852. },
  36853. enumerable: true,
  36854. configurable: true
  36855. });
  36856. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  36857. /**
  36858. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  36859. */
  36860. get: function () {
  36861. return this._PBRMATERIAL_ALPHATEST;
  36862. },
  36863. enumerable: true,
  36864. configurable: true
  36865. });
  36866. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  36867. /**
  36868. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  36869. */
  36870. get: function () {
  36871. return this._PBRMATERIAL_ALPHABLEND;
  36872. },
  36873. enumerable: true,
  36874. configurable: true
  36875. });
  36876. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  36877. /**
  36878. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  36879. * They are also discarded below the alpha cutoff threshold to improve performances.
  36880. */
  36881. get: function () {
  36882. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  36883. },
  36884. enumerable: true,
  36885. configurable: true
  36886. });
  36887. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  36888. /**
  36889. * Gets the image processing configuration used either in this material.
  36890. */
  36891. get: function () {
  36892. return this._imageProcessingConfiguration;
  36893. },
  36894. /**
  36895. * Sets the Default image processing configuration used either in the this material.
  36896. *
  36897. * If sets to null, the scene one is in use.
  36898. */
  36899. set: function (value) {
  36900. this._attachImageProcessingConfiguration(value);
  36901. // Ensure the effect will be rebuilt.
  36902. this._markAllSubMeshesAsTexturesDirty();
  36903. },
  36904. enumerable: true,
  36905. configurable: true
  36906. });
  36907. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  36908. /**
  36909. * Gets wether the color curves effect is enabled.
  36910. */
  36911. get: function () {
  36912. return this.imageProcessingConfiguration.colorCurvesEnabled;
  36913. },
  36914. /**
  36915. * Sets wether the color curves effect is enabled.
  36916. */
  36917. set: function (value) {
  36918. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  36919. },
  36920. enumerable: true,
  36921. configurable: true
  36922. });
  36923. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  36924. /**
  36925. * Gets wether the color grading effect is enabled.
  36926. */
  36927. get: function () {
  36928. return this.imageProcessingConfiguration.colorGradingEnabled;
  36929. },
  36930. /**
  36931. * Gets wether the color grading effect is enabled.
  36932. */
  36933. set: function (value) {
  36934. this.imageProcessingConfiguration.colorGradingEnabled = value;
  36935. },
  36936. enumerable: true,
  36937. configurable: true
  36938. });
  36939. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  36940. /**
  36941. * Gets wether tonemapping is enabled or not.
  36942. */
  36943. get: function () {
  36944. return this._imageProcessingConfiguration.toneMappingEnabled;
  36945. },
  36946. /**
  36947. * Sets wether tonemapping is enabled or not
  36948. */
  36949. set: function (value) {
  36950. this._imageProcessingConfiguration.toneMappingEnabled = value;
  36951. },
  36952. enumerable: true,
  36953. configurable: true
  36954. });
  36955. ;
  36956. ;
  36957. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  36958. /**
  36959. * The camera exposure used on this material.
  36960. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36961. * This corresponds to a photographic exposure.
  36962. */
  36963. get: function () {
  36964. return this._imageProcessingConfiguration.exposure;
  36965. },
  36966. /**
  36967. * The camera exposure used on this material.
  36968. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36969. * This corresponds to a photographic exposure.
  36970. */
  36971. set: function (value) {
  36972. this._imageProcessingConfiguration.exposure = value;
  36973. },
  36974. enumerable: true,
  36975. configurable: true
  36976. });
  36977. ;
  36978. ;
  36979. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  36980. /**
  36981. * Gets The camera contrast used on this material.
  36982. */
  36983. get: function () {
  36984. return this._imageProcessingConfiguration.contrast;
  36985. },
  36986. /**
  36987. * Sets The camera contrast used on this material.
  36988. */
  36989. set: function (value) {
  36990. this._imageProcessingConfiguration.contrast = value;
  36991. },
  36992. enumerable: true,
  36993. configurable: true
  36994. });
  36995. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  36996. /**
  36997. * Gets the Color Grading 2D Lookup Texture.
  36998. */
  36999. get: function () {
  37000. return this._imageProcessingConfiguration.colorGradingTexture;
  37001. },
  37002. /**
  37003. * Sets the Color Grading 2D Lookup Texture.
  37004. */
  37005. set: function (value) {
  37006. this._imageProcessingConfiguration.colorGradingTexture = value;
  37007. },
  37008. enumerable: true,
  37009. configurable: true
  37010. });
  37011. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  37012. /**
  37013. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37014. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37015. * 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;
  37016. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37017. */
  37018. get: function () {
  37019. return this._imageProcessingConfiguration.colorCurves;
  37020. },
  37021. /**
  37022. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37023. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37024. * 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;
  37025. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37026. */
  37027. set: function (value) {
  37028. this._imageProcessingConfiguration.colorCurves = value;
  37029. },
  37030. enumerable: true,
  37031. configurable: true
  37032. });
  37033. PBRMaterial.prototype.getClassName = function () {
  37034. return "PBRMaterial";
  37035. };
  37036. PBRMaterial.prototype.getActiveTextures = function () {
  37037. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37038. if (this._albedoTexture) {
  37039. activeTextures.push(this._albedoTexture);
  37040. }
  37041. if (this._ambientTexture) {
  37042. activeTextures.push(this._ambientTexture);
  37043. }
  37044. if (this._opacityTexture) {
  37045. activeTextures.push(this._opacityTexture);
  37046. }
  37047. if (this._reflectionTexture) {
  37048. activeTextures.push(this._reflectionTexture);
  37049. }
  37050. if (this._emissiveTexture) {
  37051. activeTextures.push(this._emissiveTexture);
  37052. }
  37053. if (this._reflectivityTexture) {
  37054. activeTextures.push(this._reflectivityTexture);
  37055. }
  37056. if (this._metallicTexture) {
  37057. activeTextures.push(this._metallicTexture);
  37058. }
  37059. if (this._microSurfaceTexture) {
  37060. activeTextures.push(this._microSurfaceTexture);
  37061. }
  37062. if (this._bumpTexture) {
  37063. activeTextures.push(this._bumpTexture);
  37064. }
  37065. if (this._lightmapTexture) {
  37066. activeTextures.push(this._lightmapTexture);
  37067. }
  37068. if (this._refractionTexture) {
  37069. activeTextures.push(this._refractionTexture);
  37070. }
  37071. return activeTextures;
  37072. };
  37073. PBRMaterial.prototype.hasTexture = function (texture) {
  37074. if (_super.prototype.hasTexture.call(this, texture)) {
  37075. return true;
  37076. }
  37077. if (this._albedoTexture === texture) {
  37078. return true;
  37079. }
  37080. if (this._ambientTexture === texture) {
  37081. return true;
  37082. }
  37083. if (this._opacityTexture === texture) {
  37084. return true;
  37085. }
  37086. if (this._reflectionTexture === texture) {
  37087. return true;
  37088. }
  37089. if (this._reflectivityTexture === texture) {
  37090. return true;
  37091. }
  37092. if (this._metallicTexture === texture) {
  37093. return true;
  37094. }
  37095. if (this._microSurfaceTexture === texture) {
  37096. return true;
  37097. }
  37098. if (this._bumpTexture === texture) {
  37099. return true;
  37100. }
  37101. if (this._lightmapTexture === texture) {
  37102. return true;
  37103. }
  37104. if (this._refractionTexture === texture) {
  37105. return true;
  37106. }
  37107. return false;
  37108. };
  37109. PBRMaterial.prototype.clone = function (name) {
  37110. var _this = this;
  37111. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  37112. clone.id = name;
  37113. clone.name = name;
  37114. return clone;
  37115. };
  37116. PBRMaterial.prototype.serialize = function () {
  37117. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37118. serializationObject.customType = "BABYLON.PBRMaterial";
  37119. return serializationObject;
  37120. };
  37121. // Statics
  37122. PBRMaterial.Parse = function (source, scene, rootUrl) {
  37123. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  37124. };
  37125. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  37126. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  37127. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  37128. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  37129. __decorate([
  37130. BABYLON.serialize(),
  37131. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37132. ], PBRMaterial.prototype, "directIntensity", void 0);
  37133. __decorate([
  37134. BABYLON.serialize(),
  37135. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37136. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  37137. __decorate([
  37138. BABYLON.serialize(),
  37139. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37140. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  37141. __decorate([
  37142. BABYLON.serialize(),
  37143. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37144. ], PBRMaterial.prototype, "specularIntensity", void 0);
  37145. __decorate([
  37146. BABYLON.serialize(),
  37147. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37148. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  37149. __decorate([
  37150. BABYLON.serializeAsTexture(),
  37151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37152. ], PBRMaterial.prototype, "albedoTexture", void 0);
  37153. __decorate([
  37154. BABYLON.serializeAsTexture(),
  37155. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37156. ], PBRMaterial.prototype, "ambientTexture", void 0);
  37157. __decorate([
  37158. BABYLON.serialize(),
  37159. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37160. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  37161. __decorate([
  37162. BABYLON.serializeAsTexture(),
  37163. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37164. ], PBRMaterial.prototype, "opacityTexture", void 0);
  37165. __decorate([
  37166. BABYLON.serializeAsTexture(),
  37167. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37168. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  37169. __decorate([
  37170. BABYLON.serializeAsTexture(),
  37171. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37172. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  37173. __decorate([
  37174. BABYLON.serializeAsTexture(),
  37175. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37176. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  37177. __decorate([
  37178. BABYLON.serializeAsTexture(),
  37179. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37180. ], PBRMaterial.prototype, "metallicTexture", void 0);
  37181. __decorate([
  37182. BABYLON.serialize(),
  37183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37184. ], PBRMaterial.prototype, "metallic", void 0);
  37185. __decorate([
  37186. BABYLON.serialize(),
  37187. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37188. ], PBRMaterial.prototype, "roughness", void 0);
  37189. __decorate([
  37190. BABYLON.serializeAsTexture(),
  37191. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37192. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  37193. __decorate([
  37194. BABYLON.serializeAsTexture(),
  37195. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37196. ], PBRMaterial.prototype, "bumpTexture", void 0);
  37197. __decorate([
  37198. BABYLON.serializeAsTexture(),
  37199. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  37200. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  37201. __decorate([
  37202. BABYLON.serializeAsTexture(),
  37203. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37204. ], PBRMaterial.prototype, "refractionTexture", void 0);
  37205. __decorate([
  37206. BABYLON.serializeAsColor3("ambient"),
  37207. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37208. ], PBRMaterial.prototype, "ambientColor", void 0);
  37209. __decorate([
  37210. BABYLON.serializeAsColor3("albedo"),
  37211. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37212. ], PBRMaterial.prototype, "albedoColor", void 0);
  37213. __decorate([
  37214. BABYLON.serializeAsColor3("reflectivity"),
  37215. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37216. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  37217. __decorate([
  37218. BABYLON.serializeAsColor3("reflection"),
  37219. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37220. ], PBRMaterial.prototype, "reflectionColor", void 0);
  37221. __decorate([
  37222. BABYLON.serializeAsColor3("emissive"),
  37223. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37224. ], PBRMaterial.prototype, "emissiveColor", void 0);
  37225. __decorate([
  37226. BABYLON.serialize(),
  37227. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37228. ], PBRMaterial.prototype, "microSurface", void 0);
  37229. __decorate([
  37230. BABYLON.serialize(),
  37231. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37232. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  37233. __decorate([
  37234. BABYLON.serialize(),
  37235. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37236. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  37237. __decorate([
  37238. BABYLON.serialize(),
  37239. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37240. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  37241. __decorate([
  37242. BABYLON.serialize(),
  37243. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37244. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  37245. __decorate([
  37246. BABYLON.serialize(),
  37247. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37248. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  37249. __decorate([
  37250. BABYLON.serialize(),
  37251. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37252. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  37253. __decorate([
  37254. BABYLON.serialize(),
  37255. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37256. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  37257. __decorate([
  37258. BABYLON.serialize(),
  37259. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37260. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  37261. __decorate([
  37262. BABYLON.serialize(),
  37263. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37264. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  37265. __decorate([
  37266. BABYLON.serialize(),
  37267. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37268. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  37269. __decorate([
  37270. BABYLON.serialize(),
  37271. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37272. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  37273. __decorate([
  37274. BABYLON.serialize(),
  37275. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37276. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  37277. __decorate([
  37278. BABYLON.serialize(),
  37279. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37280. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  37281. __decorate([
  37282. BABYLON.serialize(),
  37283. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37284. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  37285. __decorate([
  37286. BABYLON.serialize(),
  37287. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37288. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  37289. __decorate([
  37290. BABYLON.serialize(),
  37291. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37292. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  37293. __decorate([
  37294. BABYLON.serialize(),
  37295. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37296. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  37297. __decorate([
  37298. BABYLON.serialize(),
  37299. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37300. ], PBRMaterial.prototype, "useParallax", void 0);
  37301. __decorate([
  37302. BABYLON.serialize(),
  37303. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37304. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  37305. __decorate([
  37306. BABYLON.serialize(),
  37307. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37308. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  37309. __decorate([
  37310. BABYLON.serialize(),
  37311. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37312. ], PBRMaterial.prototype, "disableLighting", void 0);
  37313. __decorate([
  37314. BABYLON.serialize(),
  37315. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37316. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  37317. __decorate([
  37318. BABYLON.serialize(),
  37319. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37320. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  37321. __decorate([
  37322. BABYLON.serialize(),
  37323. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37324. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  37325. __decorate([
  37326. BABYLON.serialize(),
  37327. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37328. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  37329. __decorate([
  37330. BABYLON.serialize(),
  37331. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37332. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  37333. __decorate([
  37334. BABYLON.serialize(),
  37335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37336. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  37337. __decorate([
  37338. BABYLON.serializeAsTexture(),
  37339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37340. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  37341. __decorate([
  37342. BABYLON.serialize(),
  37343. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37344. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  37345. __decorate([
  37346. BABYLON.serialize(),
  37347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37348. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  37349. __decorate([
  37350. BABYLON.serialize(),
  37351. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37352. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  37353. return PBRMaterial;
  37354. }(BABYLON.PBRBaseMaterial));
  37355. BABYLON.PBRMaterial = PBRMaterial;
  37356. })(BABYLON || (BABYLON = {}));
  37357. //# sourceMappingURL=babylon.pbrMaterial.js.map
  37358. var BABYLON;
  37359. (function (BABYLON) {
  37360. /**
  37361. * The PBR material of BJS following the metal roughness convention.
  37362. *
  37363. * This fits to the PBR convention in the GLTF definition:
  37364. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  37365. */
  37366. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  37367. __extends(PBRMetallicRoughnessMaterial, _super);
  37368. /**
  37369. * Instantiates a new PBRMetalRoughnessMaterial instance.
  37370. *
  37371. * @param name The material name
  37372. * @param scene The scene the material will be use in.
  37373. */
  37374. function PBRMetallicRoughnessMaterial(name, scene) {
  37375. var _this = _super.call(this, name, scene) || this;
  37376. _this._useRoughnessFromMetallicTextureAlpha = false;
  37377. _this._useRoughnessFromMetallicTextureGreen = true;
  37378. _this._useMetallnessFromMetallicTextureBlue = true;
  37379. return _this;
  37380. }
  37381. /**
  37382. * Return the currrent class name of the material.
  37383. */
  37384. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  37385. return "PBRMetallicRoughnessMaterial";
  37386. };
  37387. /**
  37388. * Return the active textures of the material.
  37389. */
  37390. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  37391. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37392. if (this.baseTexture) {
  37393. activeTextures.push(this.baseTexture);
  37394. }
  37395. if (this.metallicRoughnessTexture) {
  37396. activeTextures.push(this.metallicRoughnessTexture);
  37397. }
  37398. return activeTextures;
  37399. };
  37400. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  37401. if (_super.prototype.hasTexture.call(this, texture)) {
  37402. return true;
  37403. }
  37404. if (this.baseTexture === texture) {
  37405. return true;
  37406. }
  37407. if (this.metallicRoughnessTexture === texture) {
  37408. return true;
  37409. }
  37410. return false;
  37411. };
  37412. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  37413. var _this = this;
  37414. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  37415. clone.id = name;
  37416. clone.name = name;
  37417. return clone;
  37418. };
  37419. /**
  37420. * Serialize the material to a parsable JSON object.
  37421. */
  37422. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  37423. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37424. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  37425. return serializationObject;
  37426. };
  37427. /**
  37428. * Parses a JSON object correponding to the serialize function.
  37429. */
  37430. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  37431. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  37432. };
  37433. __decorate([
  37434. BABYLON.serializeAsColor3(),
  37435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  37436. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  37437. __decorate([
  37438. BABYLON.serializeAsTexture(),
  37439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  37440. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  37441. __decorate([
  37442. BABYLON.serialize(),
  37443. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37444. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  37445. __decorate([
  37446. BABYLON.serialize(),
  37447. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37448. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  37449. __decorate([
  37450. BABYLON.serializeAsTexture(),
  37451. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  37452. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  37453. return PBRMetallicRoughnessMaterial;
  37454. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  37455. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  37456. })(BABYLON || (BABYLON = {}));
  37457. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  37458. var BABYLON;
  37459. (function (BABYLON) {
  37460. /**
  37461. * The PBR material of BJS following the specular glossiness convention.
  37462. *
  37463. * This fits to the PBR convention in the GLTF definition:
  37464. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  37465. */
  37466. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  37467. __extends(PBRSpecularGlossinessMaterial, _super);
  37468. /**
  37469. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  37470. *
  37471. * @param name The material name
  37472. * @param scene The scene the material will be use in.
  37473. */
  37474. function PBRSpecularGlossinessMaterial(name, scene) {
  37475. var _this = _super.call(this, name, scene) || this;
  37476. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  37477. return _this;
  37478. }
  37479. /**
  37480. * Return the currrent class name of the material.
  37481. */
  37482. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  37483. return "PBRSpecularGlossinessMaterial";
  37484. };
  37485. /**
  37486. * Return the active textures of the material.
  37487. */
  37488. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  37489. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37490. if (this.diffuseTexture) {
  37491. activeTextures.push(this.diffuseTexture);
  37492. }
  37493. if (this.specularGlossinessTexture) {
  37494. activeTextures.push(this.specularGlossinessTexture);
  37495. }
  37496. return activeTextures;
  37497. };
  37498. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  37499. if (_super.prototype.hasTexture.call(this, texture)) {
  37500. return true;
  37501. }
  37502. if (this.diffuseTexture === texture) {
  37503. return true;
  37504. }
  37505. if (this.specularGlossinessTexture === texture) {
  37506. return true;
  37507. }
  37508. return false;
  37509. };
  37510. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  37511. var _this = this;
  37512. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  37513. clone.id = name;
  37514. clone.name = name;
  37515. return clone;
  37516. };
  37517. /**
  37518. * Serialize the material to a parsable JSON object.
  37519. */
  37520. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  37521. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37522. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  37523. return serializationObject;
  37524. };
  37525. /**
  37526. * Parses a JSON object correponding to the serialize function.
  37527. */
  37528. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  37529. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  37530. };
  37531. __decorate([
  37532. BABYLON.serializeAsColor3("diffuse"),
  37533. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  37534. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  37535. __decorate([
  37536. BABYLON.serializeAsTexture(),
  37537. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  37538. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  37539. __decorate([
  37540. BABYLON.serializeAsColor3("specular"),
  37541. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  37542. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  37543. __decorate([
  37544. BABYLON.serialize(),
  37545. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  37546. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  37547. __decorate([
  37548. BABYLON.serializeAsTexture(),
  37549. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  37550. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  37551. return PBRSpecularGlossinessMaterial;
  37552. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  37553. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  37554. })(BABYLON || (BABYLON = {}));
  37555. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  37556. var BABYLON;
  37557. (function (BABYLON) {
  37558. BABYLON.CameraInputTypes = {};
  37559. var CameraInputsManager = /** @class */ (function () {
  37560. function CameraInputsManager(camera) {
  37561. this.attached = {};
  37562. this.camera = camera;
  37563. this.checkInputs = function () { };
  37564. }
  37565. CameraInputsManager.prototype.add = function (input) {
  37566. var type = input.getSimpleName();
  37567. if (this.attached[type]) {
  37568. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  37569. return;
  37570. }
  37571. this.attached[type] = input;
  37572. input.camera = this.camera;
  37573. //for checkInputs, we are dynamically creating a function
  37574. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  37575. if (input.checkInputs) {
  37576. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  37577. }
  37578. if (this.attachedElement) {
  37579. input.attachControl(this.attachedElement);
  37580. }
  37581. };
  37582. CameraInputsManager.prototype.remove = function (inputToRemove) {
  37583. for (var cam in this.attached) {
  37584. var input = this.attached[cam];
  37585. if (input === inputToRemove) {
  37586. input.detachControl(this.attachedElement);
  37587. input.camera = null;
  37588. delete this.attached[cam];
  37589. this.rebuildInputCheck();
  37590. }
  37591. }
  37592. };
  37593. CameraInputsManager.prototype.removeByType = function (inputType) {
  37594. for (var cam in this.attached) {
  37595. var input = this.attached[cam];
  37596. if (input.getClassName() === inputType) {
  37597. input.detachControl(this.attachedElement);
  37598. input.camera = null;
  37599. delete this.attached[cam];
  37600. this.rebuildInputCheck();
  37601. }
  37602. }
  37603. };
  37604. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  37605. var current = this.checkInputs;
  37606. return function () {
  37607. current();
  37608. fn();
  37609. };
  37610. };
  37611. CameraInputsManager.prototype.attachInput = function (input) {
  37612. if (this.attachedElement) {
  37613. input.attachControl(this.attachedElement, this.noPreventDefault);
  37614. }
  37615. };
  37616. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  37617. if (noPreventDefault === void 0) { noPreventDefault = false; }
  37618. if (this.attachedElement) {
  37619. return;
  37620. }
  37621. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  37622. this.attachedElement = element;
  37623. this.noPreventDefault = noPreventDefault;
  37624. for (var cam in this.attached) {
  37625. this.attached[cam].attachControl(element, noPreventDefault);
  37626. }
  37627. };
  37628. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  37629. if (disconnect === void 0) { disconnect = false; }
  37630. if (this.attachedElement !== element) {
  37631. return;
  37632. }
  37633. for (var cam in this.attached) {
  37634. this.attached[cam].detachControl(element);
  37635. if (disconnect) {
  37636. this.attached[cam].camera = null;
  37637. }
  37638. }
  37639. this.attachedElement = null;
  37640. };
  37641. CameraInputsManager.prototype.rebuildInputCheck = function () {
  37642. this.checkInputs = function () { };
  37643. for (var cam in this.attached) {
  37644. var input = this.attached[cam];
  37645. if (input.checkInputs) {
  37646. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  37647. }
  37648. }
  37649. };
  37650. CameraInputsManager.prototype.clear = function () {
  37651. if (this.attachedElement) {
  37652. this.detachElement(this.attachedElement, true);
  37653. }
  37654. this.attached = {};
  37655. this.attachedElement = null;
  37656. this.checkInputs = function () { };
  37657. };
  37658. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  37659. var inputs = {};
  37660. for (var cam in this.attached) {
  37661. var input = this.attached[cam];
  37662. var res = BABYLON.SerializationHelper.Serialize(input);
  37663. inputs[input.getClassName()] = res;
  37664. }
  37665. serializedCamera.inputsmgr = inputs;
  37666. };
  37667. CameraInputsManager.prototype.parse = function (parsedCamera) {
  37668. var parsedInputs = parsedCamera.inputsmgr;
  37669. if (parsedInputs) {
  37670. this.clear();
  37671. for (var n in parsedInputs) {
  37672. var construct = BABYLON.CameraInputTypes[n];
  37673. if (construct) {
  37674. var parsedinput = parsedInputs[n];
  37675. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  37676. this.add(input);
  37677. }
  37678. }
  37679. }
  37680. else {
  37681. //2016-03-08 this part is for managing backward compatibility
  37682. for (var n in this.attached) {
  37683. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  37684. if (construct) {
  37685. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  37686. this.remove(this.attached[n]);
  37687. this.add(input);
  37688. }
  37689. }
  37690. }
  37691. };
  37692. return CameraInputsManager;
  37693. }());
  37694. BABYLON.CameraInputsManager = CameraInputsManager;
  37695. })(BABYLON || (BABYLON = {}));
  37696. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  37697. var BABYLON;
  37698. (function (BABYLON) {
  37699. var FreeCameraMouseInput = /** @class */ (function () {
  37700. function FreeCameraMouseInput(touchEnabled) {
  37701. if (touchEnabled === void 0) { touchEnabled = true; }
  37702. this.touchEnabled = touchEnabled;
  37703. this.buttons = [0, 1, 2];
  37704. this.angularSensibility = 2000.0;
  37705. this.previousPosition = null;
  37706. }
  37707. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  37708. var _this = this;
  37709. var engine = this.camera.getEngine();
  37710. if (!this._pointerInput) {
  37711. this._pointerInput = function (p, s) {
  37712. var evt = p.event;
  37713. if (engine.isInVRExclusivePointerMode) {
  37714. return;
  37715. }
  37716. if (!_this.touchEnabled && evt.pointerType === "touch") {
  37717. return;
  37718. }
  37719. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  37720. return;
  37721. }
  37722. var srcElement = (evt.srcElement || evt.target);
  37723. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  37724. try {
  37725. srcElement.setPointerCapture(evt.pointerId);
  37726. }
  37727. catch (e) {
  37728. //Nothing to do with the error. Execution will continue.
  37729. }
  37730. _this.previousPosition = {
  37731. x: evt.clientX,
  37732. y: evt.clientY
  37733. };
  37734. if (!noPreventDefault) {
  37735. evt.preventDefault();
  37736. element.focus();
  37737. }
  37738. }
  37739. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  37740. try {
  37741. srcElement.releasePointerCapture(evt.pointerId);
  37742. }
  37743. catch (e) {
  37744. //Nothing to do with the error.
  37745. }
  37746. _this.previousPosition = null;
  37747. if (!noPreventDefault) {
  37748. evt.preventDefault();
  37749. }
  37750. }
  37751. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  37752. if (!_this.previousPosition || engine.isPointerLock) {
  37753. return;
  37754. }
  37755. var offsetX = evt.clientX - _this.previousPosition.x;
  37756. var offsetY = evt.clientY - _this.previousPosition.y;
  37757. if (_this.camera.getScene().useRightHandedSystem) {
  37758. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  37759. }
  37760. else {
  37761. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  37762. }
  37763. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  37764. _this.previousPosition = {
  37765. x: evt.clientX,
  37766. y: evt.clientY
  37767. };
  37768. if (!noPreventDefault) {
  37769. evt.preventDefault();
  37770. }
  37771. }
  37772. };
  37773. }
  37774. this._onMouseMove = function (evt) {
  37775. if (!engine.isPointerLock) {
  37776. return;
  37777. }
  37778. if (engine.isInVRExclusivePointerMode) {
  37779. return;
  37780. }
  37781. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  37782. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  37783. if (_this.camera.getScene().useRightHandedSystem) {
  37784. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  37785. }
  37786. else {
  37787. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  37788. }
  37789. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  37790. _this.previousPosition = null;
  37791. if (!noPreventDefault) {
  37792. evt.preventDefault();
  37793. }
  37794. };
  37795. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  37796. element.addEventListener("mousemove", this._onMouseMove, false);
  37797. };
  37798. FreeCameraMouseInput.prototype.detachControl = function (element) {
  37799. if (this._observer && element) {
  37800. this.camera.getScene().onPointerObservable.remove(this._observer);
  37801. if (this._onMouseMove) {
  37802. element.removeEventListener("mousemove", this._onMouseMove);
  37803. }
  37804. this._observer = null;
  37805. this._onMouseMove = null;
  37806. this.previousPosition = null;
  37807. }
  37808. };
  37809. FreeCameraMouseInput.prototype.getClassName = function () {
  37810. return "FreeCameraMouseInput";
  37811. };
  37812. FreeCameraMouseInput.prototype.getSimpleName = function () {
  37813. return "mouse";
  37814. };
  37815. __decorate([
  37816. BABYLON.serialize()
  37817. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  37818. __decorate([
  37819. BABYLON.serialize()
  37820. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  37821. return FreeCameraMouseInput;
  37822. }());
  37823. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  37824. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  37825. })(BABYLON || (BABYLON = {}));
  37826. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  37827. var BABYLON;
  37828. (function (BABYLON) {
  37829. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  37830. function FreeCameraKeyboardMoveInput() {
  37831. this._keys = new Array();
  37832. this.keysUp = [38];
  37833. this.keysDown = [40];
  37834. this.keysLeft = [37];
  37835. this.keysRight = [39];
  37836. }
  37837. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  37838. var _this = this;
  37839. if (this._onCanvasBlurObserver) {
  37840. return;
  37841. }
  37842. this._scene = this.camera.getScene();
  37843. this._engine = this._scene.getEngine();
  37844. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  37845. _this._keys = [];
  37846. });
  37847. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  37848. var evt = info.event;
  37849. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  37850. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37851. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37852. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37853. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  37854. var index = _this._keys.indexOf(evt.keyCode);
  37855. if (index === -1) {
  37856. _this._keys.push(evt.keyCode);
  37857. }
  37858. if (!noPreventDefault) {
  37859. evt.preventDefault();
  37860. }
  37861. }
  37862. }
  37863. else {
  37864. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37865. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37866. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37867. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  37868. var index = _this._keys.indexOf(evt.keyCode);
  37869. if (index >= 0) {
  37870. _this._keys.splice(index, 1);
  37871. }
  37872. if (!noPreventDefault) {
  37873. evt.preventDefault();
  37874. }
  37875. }
  37876. }
  37877. });
  37878. };
  37879. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  37880. if (this._scene) {
  37881. if (this._onKeyboardObserver) {
  37882. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  37883. }
  37884. if (this._onCanvasBlurObserver) {
  37885. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  37886. }
  37887. this._onKeyboardObserver = null;
  37888. this._onCanvasBlurObserver = null;
  37889. }
  37890. this._keys = [];
  37891. };
  37892. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  37893. if (this._onKeyboardObserver) {
  37894. var camera = this.camera;
  37895. // Keyboard
  37896. for (var index = 0; index < this._keys.length; index++) {
  37897. var keyCode = this._keys[index];
  37898. var speed = camera._computeLocalCameraSpeed();
  37899. if (this.keysLeft.indexOf(keyCode) !== -1) {
  37900. camera._localDirection.copyFromFloats(-speed, 0, 0);
  37901. }
  37902. else if (this.keysUp.indexOf(keyCode) !== -1) {
  37903. camera._localDirection.copyFromFloats(0, 0, speed);
  37904. }
  37905. else if (this.keysRight.indexOf(keyCode) !== -1) {
  37906. camera._localDirection.copyFromFloats(speed, 0, 0);
  37907. }
  37908. else if (this.keysDown.indexOf(keyCode) !== -1) {
  37909. camera._localDirection.copyFromFloats(0, 0, -speed);
  37910. }
  37911. if (camera.getScene().useRightHandedSystem) {
  37912. camera._localDirection.z *= -1;
  37913. }
  37914. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  37915. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  37916. camera.cameraDirection.addInPlace(camera._transformedDirection);
  37917. }
  37918. }
  37919. };
  37920. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  37921. return "FreeCameraKeyboardMoveInput";
  37922. };
  37923. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  37924. this._keys = [];
  37925. };
  37926. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  37927. return "keyboard";
  37928. };
  37929. __decorate([
  37930. BABYLON.serialize()
  37931. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  37932. __decorate([
  37933. BABYLON.serialize()
  37934. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  37935. __decorate([
  37936. BABYLON.serialize()
  37937. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  37938. __decorate([
  37939. BABYLON.serialize()
  37940. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  37941. return FreeCameraKeyboardMoveInput;
  37942. }());
  37943. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  37944. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  37945. })(BABYLON || (BABYLON = {}));
  37946. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  37947. var BABYLON;
  37948. (function (BABYLON) {
  37949. var FreeCameraInputsManager = /** @class */ (function (_super) {
  37950. __extends(FreeCameraInputsManager, _super);
  37951. function FreeCameraInputsManager(camera) {
  37952. return _super.call(this, camera) || this;
  37953. }
  37954. FreeCameraInputsManager.prototype.addKeyboard = function () {
  37955. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  37956. return this;
  37957. };
  37958. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  37959. if (touchEnabled === void 0) { touchEnabled = true; }
  37960. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  37961. return this;
  37962. };
  37963. FreeCameraInputsManager.prototype.addGamepad = function () {
  37964. this.add(new BABYLON.FreeCameraGamepadInput());
  37965. return this;
  37966. };
  37967. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  37968. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  37969. return this;
  37970. };
  37971. FreeCameraInputsManager.prototype.addTouch = function () {
  37972. this.add(new BABYLON.FreeCameraTouchInput());
  37973. return this;
  37974. };
  37975. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  37976. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  37977. return this;
  37978. };
  37979. return FreeCameraInputsManager;
  37980. }(BABYLON.CameraInputsManager));
  37981. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  37982. })(BABYLON || (BABYLON = {}));
  37983. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  37984. var BABYLON;
  37985. (function (BABYLON) {
  37986. var TargetCamera = /** @class */ (function (_super) {
  37987. __extends(TargetCamera, _super);
  37988. function TargetCamera(name, position, scene) {
  37989. var _this = _super.call(this, name, position, scene) || this;
  37990. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  37991. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  37992. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  37993. _this.speed = 2.0;
  37994. _this.noRotationConstraint = false;
  37995. _this.lockedTarget = null;
  37996. _this._currentTarget = BABYLON.Vector3.Zero();
  37997. _this._viewMatrix = BABYLON.Matrix.Zero();
  37998. _this._camMatrix = BABYLON.Matrix.Zero();
  37999. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  38000. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  38001. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  38002. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  38003. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  38004. _this._lookAtTemp = BABYLON.Matrix.Zero();
  38005. _this._tempMatrix = BABYLON.Matrix.Zero();
  38006. return _this;
  38007. }
  38008. TargetCamera.prototype.getFrontPosition = function (distance) {
  38009. var direction = this.getTarget().subtract(this.position);
  38010. direction.normalize();
  38011. direction.scaleInPlace(distance);
  38012. return this.globalPosition.add(direction);
  38013. };
  38014. TargetCamera.prototype._getLockedTargetPosition = function () {
  38015. if (!this.lockedTarget) {
  38016. return null;
  38017. }
  38018. if (this.lockedTarget.absolutePosition) {
  38019. this.lockedTarget.computeWorldMatrix();
  38020. }
  38021. return this.lockedTarget.absolutePosition || this.lockedTarget;
  38022. };
  38023. TargetCamera.prototype.storeState = function () {
  38024. this._storedPosition = this.position.clone();
  38025. this._storedRotation = this.rotation.clone();
  38026. if (this.rotationQuaternion) {
  38027. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  38028. }
  38029. return _super.prototype.storeState.call(this);
  38030. };
  38031. /**
  38032. * Restored camera state. You must call storeState() first
  38033. */
  38034. TargetCamera.prototype._restoreStateValues = function () {
  38035. if (!_super.prototype._restoreStateValues.call(this)) {
  38036. return false;
  38037. }
  38038. this.position = this._storedPosition.clone();
  38039. this.rotation = this._storedRotation.clone();
  38040. if (this.rotationQuaternion) {
  38041. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  38042. }
  38043. this.cameraDirection.copyFromFloats(0, 0, 0);
  38044. this.cameraRotation.copyFromFloats(0, 0);
  38045. return true;
  38046. };
  38047. // Cache
  38048. TargetCamera.prototype._initCache = function () {
  38049. _super.prototype._initCache.call(this);
  38050. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38051. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38052. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38053. };
  38054. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  38055. if (!ignoreParentClass) {
  38056. _super.prototype._updateCache.call(this);
  38057. }
  38058. var lockedTargetPosition = this._getLockedTargetPosition();
  38059. if (!lockedTargetPosition) {
  38060. this._cache.lockedTarget = null;
  38061. }
  38062. else {
  38063. if (!this._cache.lockedTarget) {
  38064. this._cache.lockedTarget = lockedTargetPosition.clone();
  38065. }
  38066. else {
  38067. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  38068. }
  38069. }
  38070. this._cache.rotation.copyFrom(this.rotation);
  38071. if (this.rotationQuaternion)
  38072. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38073. };
  38074. // Synchronized
  38075. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  38076. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  38077. return false;
  38078. }
  38079. var lockedTargetPosition = this._getLockedTargetPosition();
  38080. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  38081. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  38082. };
  38083. // Methods
  38084. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  38085. var engine = this.getEngine();
  38086. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  38087. };
  38088. // Target
  38089. TargetCamera.prototype.setTarget = function (target) {
  38090. this.upVector.normalize();
  38091. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  38092. this._camMatrix.invert();
  38093. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  38094. var vDir = target.subtract(this.position);
  38095. if (vDir.x >= 0.0) {
  38096. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  38097. }
  38098. else {
  38099. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  38100. }
  38101. this.rotation.z = 0;
  38102. if (isNaN(this.rotation.x)) {
  38103. this.rotation.x = 0;
  38104. }
  38105. if (isNaN(this.rotation.y)) {
  38106. this.rotation.y = 0;
  38107. }
  38108. if (isNaN(this.rotation.z)) {
  38109. this.rotation.z = 0;
  38110. }
  38111. if (this.rotationQuaternion) {
  38112. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  38113. }
  38114. };
  38115. /**
  38116. * Return the current target position of the camera. This value is expressed in local space.
  38117. */
  38118. TargetCamera.prototype.getTarget = function () {
  38119. return this._currentTarget;
  38120. };
  38121. TargetCamera.prototype._decideIfNeedsToMove = function () {
  38122. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  38123. };
  38124. TargetCamera.prototype._updatePosition = function () {
  38125. if (this.parent) {
  38126. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  38127. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  38128. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  38129. return;
  38130. }
  38131. this.position.addInPlace(this.cameraDirection);
  38132. };
  38133. TargetCamera.prototype._checkInputs = function () {
  38134. var needToMove = this._decideIfNeedsToMove();
  38135. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  38136. // Move
  38137. if (needToMove) {
  38138. this._updatePosition();
  38139. }
  38140. // Rotate
  38141. if (needToRotate) {
  38142. this.rotation.x += this.cameraRotation.x;
  38143. this.rotation.y += this.cameraRotation.y;
  38144. //rotate, if quaternion is set and rotation was used
  38145. if (this.rotationQuaternion) {
  38146. var len = this.rotation.lengthSquared();
  38147. if (len) {
  38148. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  38149. }
  38150. }
  38151. if (!this.noRotationConstraint) {
  38152. var limit = (Math.PI / 2) * 0.95;
  38153. if (this.rotation.x > limit)
  38154. this.rotation.x = limit;
  38155. if (this.rotation.x < -limit)
  38156. this.rotation.x = -limit;
  38157. }
  38158. }
  38159. // Inertia
  38160. if (needToMove) {
  38161. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  38162. this.cameraDirection.x = 0;
  38163. }
  38164. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  38165. this.cameraDirection.y = 0;
  38166. }
  38167. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  38168. this.cameraDirection.z = 0;
  38169. }
  38170. this.cameraDirection.scaleInPlace(this.inertia);
  38171. }
  38172. if (needToRotate) {
  38173. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  38174. this.cameraRotation.x = 0;
  38175. }
  38176. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  38177. this.cameraRotation.y = 0;
  38178. }
  38179. this.cameraRotation.scaleInPlace(this.inertia);
  38180. }
  38181. _super.prototype._checkInputs.call(this);
  38182. };
  38183. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  38184. if (this.rotationQuaternion) {
  38185. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  38186. }
  38187. else {
  38188. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  38189. }
  38190. //update the up vector!
  38191. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  38192. };
  38193. TargetCamera.prototype._getViewMatrix = function () {
  38194. if (!this.lockedTarget) {
  38195. // Compute
  38196. this._updateCameraRotationMatrix();
  38197. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  38198. // Computing target and final matrix
  38199. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  38200. }
  38201. else {
  38202. var targetPosition = this._getLockedTargetPosition();
  38203. if (targetPosition) {
  38204. this._currentTarget.copyFrom(targetPosition);
  38205. }
  38206. }
  38207. if (this.getScene().useRightHandedSystem) {
  38208. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  38209. }
  38210. else {
  38211. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  38212. }
  38213. return this._viewMatrix;
  38214. };
  38215. /**
  38216. * @override
  38217. * Override Camera.createRigCamera
  38218. */
  38219. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  38220. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  38221. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  38222. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  38223. if (!this.rotationQuaternion) {
  38224. this.rotationQuaternion = new BABYLON.Quaternion();
  38225. }
  38226. rigCamera._cameraRigParams = {};
  38227. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  38228. }
  38229. return rigCamera;
  38230. }
  38231. return null;
  38232. };
  38233. /**
  38234. * @override
  38235. * Override Camera._updateRigCameras
  38236. */
  38237. TargetCamera.prototype._updateRigCameras = function () {
  38238. var camLeft = this._rigCameras[0];
  38239. var camRight = this._rigCameras[1];
  38240. switch (this.cameraRigMode) {
  38241. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  38242. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  38243. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  38244. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  38245. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  38246. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  38247. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  38248. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  38249. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  38250. camLeft.setTarget(this.getTarget());
  38251. camRight.setTarget(this.getTarget());
  38252. break;
  38253. case BABYLON.Camera.RIG_MODE_VR:
  38254. if (camLeft.rotationQuaternion) {
  38255. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38256. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38257. }
  38258. else {
  38259. camLeft.rotation.copyFrom(this.rotation);
  38260. camRight.rotation.copyFrom(this.rotation);
  38261. }
  38262. camLeft.position.copyFrom(this.position);
  38263. camRight.position.copyFrom(this.position);
  38264. break;
  38265. }
  38266. _super.prototype._updateRigCameras.call(this);
  38267. };
  38268. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  38269. if (!this._rigCamTransformMatrix) {
  38270. this._rigCamTransformMatrix = new BABYLON.Matrix();
  38271. }
  38272. var target = this.getTarget();
  38273. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  38274. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  38275. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  38276. };
  38277. TargetCamera.prototype.getClassName = function () {
  38278. return "TargetCamera";
  38279. };
  38280. __decorate([
  38281. BABYLON.serializeAsVector3()
  38282. ], TargetCamera.prototype, "rotation", void 0);
  38283. __decorate([
  38284. BABYLON.serialize()
  38285. ], TargetCamera.prototype, "speed", void 0);
  38286. __decorate([
  38287. BABYLON.serializeAsMeshReference("lockedTargetId")
  38288. ], TargetCamera.prototype, "lockedTarget", void 0);
  38289. return TargetCamera;
  38290. }(BABYLON.Camera));
  38291. BABYLON.TargetCamera = TargetCamera;
  38292. })(BABYLON || (BABYLON = {}));
  38293. //# sourceMappingURL=babylon.targetCamera.js.map
  38294. var BABYLON;
  38295. (function (BABYLON) {
  38296. var FreeCamera = /** @class */ (function (_super) {
  38297. __extends(FreeCamera, _super);
  38298. function FreeCamera(name, position, scene) {
  38299. var _this = _super.call(this, name, position, scene) || this;
  38300. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  38301. _this.checkCollisions = false;
  38302. _this.applyGravity = false;
  38303. _this._needMoveForGravity = false;
  38304. _this._oldPosition = BABYLON.Vector3.Zero();
  38305. _this._diffPosition = BABYLON.Vector3.Zero();
  38306. _this._newPosition = BABYLON.Vector3.Zero();
  38307. // Collisions
  38308. _this._collisionMask = -1;
  38309. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  38310. if (collidedMesh === void 0) { collidedMesh = null; }
  38311. //TODO move this to the collision coordinator!
  38312. if (_this.getScene().workerCollisions)
  38313. newPosition.multiplyInPlace(_this._collider.radius);
  38314. var updatePosition = function (newPos) {
  38315. _this._newPosition.copyFrom(newPos);
  38316. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  38317. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  38318. _this.position.addInPlace(_this._diffPosition);
  38319. if (_this.onCollide && collidedMesh) {
  38320. _this.onCollide(collidedMesh);
  38321. }
  38322. }
  38323. };
  38324. updatePosition(newPosition);
  38325. };
  38326. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  38327. _this.inputs.addKeyboard().addMouse();
  38328. return _this;
  38329. }
  38330. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  38331. //-- begin properties for backward compatibility for inputs
  38332. get: function () {
  38333. var mouse = this.inputs.attached["mouse"];
  38334. if (mouse)
  38335. return mouse.angularSensibility;
  38336. return 0;
  38337. },
  38338. set: function (value) {
  38339. var mouse = this.inputs.attached["mouse"];
  38340. if (mouse)
  38341. mouse.angularSensibility = value;
  38342. },
  38343. enumerable: true,
  38344. configurable: true
  38345. });
  38346. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  38347. get: function () {
  38348. var keyboard = this.inputs.attached["keyboard"];
  38349. if (keyboard)
  38350. return keyboard.keysUp;
  38351. return [];
  38352. },
  38353. set: function (value) {
  38354. var keyboard = this.inputs.attached["keyboard"];
  38355. if (keyboard)
  38356. keyboard.keysUp = value;
  38357. },
  38358. enumerable: true,
  38359. configurable: true
  38360. });
  38361. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  38362. get: function () {
  38363. var keyboard = this.inputs.attached["keyboard"];
  38364. if (keyboard)
  38365. return keyboard.keysDown;
  38366. return [];
  38367. },
  38368. set: function (value) {
  38369. var keyboard = this.inputs.attached["keyboard"];
  38370. if (keyboard)
  38371. keyboard.keysDown = value;
  38372. },
  38373. enumerable: true,
  38374. configurable: true
  38375. });
  38376. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  38377. get: function () {
  38378. var keyboard = this.inputs.attached["keyboard"];
  38379. if (keyboard)
  38380. return keyboard.keysLeft;
  38381. return [];
  38382. },
  38383. set: function (value) {
  38384. var keyboard = this.inputs.attached["keyboard"];
  38385. if (keyboard)
  38386. keyboard.keysLeft = value;
  38387. },
  38388. enumerable: true,
  38389. configurable: true
  38390. });
  38391. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  38392. get: function () {
  38393. var keyboard = this.inputs.attached["keyboard"];
  38394. if (keyboard)
  38395. return keyboard.keysRight;
  38396. return [];
  38397. },
  38398. set: function (value) {
  38399. var keyboard = this.inputs.attached["keyboard"];
  38400. if (keyboard)
  38401. keyboard.keysRight = value;
  38402. },
  38403. enumerable: true,
  38404. configurable: true
  38405. });
  38406. // Controls
  38407. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  38408. this.inputs.attachElement(element, noPreventDefault);
  38409. };
  38410. FreeCamera.prototype.detachControl = function (element) {
  38411. this.inputs.detachElement(element);
  38412. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  38413. this.cameraRotation = new BABYLON.Vector2(0, 0);
  38414. };
  38415. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  38416. get: function () {
  38417. return this._collisionMask;
  38418. },
  38419. set: function (mask) {
  38420. this._collisionMask = !isNaN(mask) ? mask : -1;
  38421. },
  38422. enumerable: true,
  38423. configurable: true
  38424. });
  38425. FreeCamera.prototype._collideWithWorld = function (displacement) {
  38426. var globalPosition;
  38427. if (this.parent) {
  38428. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  38429. }
  38430. else {
  38431. globalPosition = this.position;
  38432. }
  38433. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  38434. if (!this._collider) {
  38435. this._collider = new BABYLON.Collider();
  38436. }
  38437. this._collider.radius = this.ellipsoid;
  38438. this._collider.collisionMask = this._collisionMask;
  38439. //no need for clone, as long as gravity is not on.
  38440. var actualDisplacement = displacement;
  38441. //add gravity to the direction to prevent the dual-collision checking
  38442. if (this.applyGravity) {
  38443. //this prevents mending with cameraDirection, a global variable of the free camera class.
  38444. actualDisplacement = displacement.add(this.getScene().gravity);
  38445. }
  38446. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  38447. };
  38448. FreeCamera.prototype._checkInputs = function () {
  38449. if (!this._localDirection) {
  38450. this._localDirection = BABYLON.Vector3.Zero();
  38451. this._transformedDirection = BABYLON.Vector3.Zero();
  38452. }
  38453. this.inputs.checkInputs();
  38454. _super.prototype._checkInputs.call(this);
  38455. };
  38456. FreeCamera.prototype._decideIfNeedsToMove = function () {
  38457. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  38458. };
  38459. FreeCamera.prototype._updatePosition = function () {
  38460. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  38461. this._collideWithWorld(this.cameraDirection);
  38462. }
  38463. else {
  38464. _super.prototype._updatePosition.call(this);
  38465. }
  38466. };
  38467. FreeCamera.prototype.dispose = function () {
  38468. this.inputs.clear();
  38469. _super.prototype.dispose.call(this);
  38470. };
  38471. FreeCamera.prototype.getClassName = function () {
  38472. return "FreeCamera";
  38473. };
  38474. __decorate([
  38475. BABYLON.serializeAsVector3()
  38476. ], FreeCamera.prototype, "ellipsoid", void 0);
  38477. __decorate([
  38478. BABYLON.serialize()
  38479. ], FreeCamera.prototype, "checkCollisions", void 0);
  38480. __decorate([
  38481. BABYLON.serialize()
  38482. ], FreeCamera.prototype, "applyGravity", void 0);
  38483. return FreeCamera;
  38484. }(BABYLON.TargetCamera));
  38485. BABYLON.FreeCamera = FreeCamera;
  38486. })(BABYLON || (BABYLON = {}));
  38487. //# sourceMappingURL=babylon.freeCamera.js.map
  38488. var BABYLON;
  38489. (function (BABYLON) {
  38490. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  38491. function ArcRotateCameraKeyboardMoveInput() {
  38492. this._keys = new Array();
  38493. this.keysUp = [38];
  38494. this.keysDown = [40];
  38495. this.keysLeft = [37];
  38496. this.keysRight = [39];
  38497. this.keysReset = [220];
  38498. this.panningSensibility = 50.0;
  38499. this.zoomingSensibility = 25.0;
  38500. this.useAltToZoom = true;
  38501. }
  38502. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  38503. var _this = this;
  38504. if (this._onCanvasBlurObserver) {
  38505. return;
  38506. }
  38507. this._scene = this.camera.getScene();
  38508. this._engine = this._scene.getEngine();
  38509. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  38510. _this._keys = [];
  38511. });
  38512. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  38513. var evt = info.event;
  38514. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  38515. _this._ctrlPressed = evt.ctrlKey;
  38516. _this._altPressed = evt.altKey;
  38517. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  38518. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  38519. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  38520. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  38521. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  38522. var index = _this._keys.indexOf(evt.keyCode);
  38523. if (index === -1) {
  38524. _this._keys.push(evt.keyCode);
  38525. }
  38526. if (evt.preventDefault) {
  38527. if (!noPreventDefault) {
  38528. evt.preventDefault();
  38529. }
  38530. }
  38531. }
  38532. }
  38533. else {
  38534. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  38535. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  38536. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  38537. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  38538. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  38539. var index = _this._keys.indexOf(evt.keyCode);
  38540. if (index >= 0) {
  38541. _this._keys.splice(index, 1);
  38542. }
  38543. if (evt.preventDefault) {
  38544. if (!noPreventDefault) {
  38545. evt.preventDefault();
  38546. }
  38547. }
  38548. }
  38549. }
  38550. });
  38551. };
  38552. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  38553. if (this._scene) {
  38554. if (this._onKeyboardObserver) {
  38555. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  38556. }
  38557. if (this._onCanvasBlurObserver) {
  38558. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  38559. }
  38560. this._onKeyboardObserver = null;
  38561. this._onCanvasBlurObserver = null;
  38562. }
  38563. this._keys = [];
  38564. };
  38565. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  38566. if (this._onKeyboardObserver) {
  38567. var camera = this.camera;
  38568. for (var index = 0; index < this._keys.length; index++) {
  38569. var keyCode = this._keys[index];
  38570. if (this.keysLeft.indexOf(keyCode) !== -1) {
  38571. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38572. camera.inertialPanningX -= 1 / this.panningSensibility;
  38573. }
  38574. else {
  38575. camera.inertialAlphaOffset -= 0.01;
  38576. }
  38577. }
  38578. else if (this.keysUp.indexOf(keyCode) !== -1) {
  38579. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38580. camera.inertialPanningY += 1 / this.panningSensibility;
  38581. }
  38582. else if (this._altPressed && this.useAltToZoom) {
  38583. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  38584. }
  38585. else {
  38586. camera.inertialBetaOffset -= 0.01;
  38587. }
  38588. }
  38589. else if (this.keysRight.indexOf(keyCode) !== -1) {
  38590. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38591. camera.inertialPanningX += 1 / this.panningSensibility;
  38592. }
  38593. else {
  38594. camera.inertialAlphaOffset += 0.01;
  38595. }
  38596. }
  38597. else if (this.keysDown.indexOf(keyCode) !== -1) {
  38598. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38599. camera.inertialPanningY -= 1 / this.panningSensibility;
  38600. }
  38601. else if (this._altPressed && this.useAltToZoom) {
  38602. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  38603. }
  38604. else {
  38605. camera.inertialBetaOffset += 0.01;
  38606. }
  38607. }
  38608. else if (this.keysReset.indexOf(keyCode) !== -1) {
  38609. camera.restoreState();
  38610. }
  38611. }
  38612. }
  38613. };
  38614. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  38615. return "ArcRotateCameraKeyboardMoveInput";
  38616. };
  38617. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  38618. return "keyboard";
  38619. };
  38620. __decorate([
  38621. BABYLON.serialize()
  38622. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  38623. __decorate([
  38624. BABYLON.serialize()
  38625. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  38626. __decorate([
  38627. BABYLON.serialize()
  38628. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  38629. __decorate([
  38630. BABYLON.serialize()
  38631. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  38632. __decorate([
  38633. BABYLON.serialize()
  38634. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  38635. __decorate([
  38636. BABYLON.serialize()
  38637. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  38638. __decorate([
  38639. BABYLON.serialize()
  38640. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  38641. __decorate([
  38642. BABYLON.serialize()
  38643. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  38644. return ArcRotateCameraKeyboardMoveInput;
  38645. }());
  38646. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  38647. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  38648. })(BABYLON || (BABYLON = {}));
  38649. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  38650. var BABYLON;
  38651. (function (BABYLON) {
  38652. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  38653. function ArcRotateCameraMouseWheelInput() {
  38654. this.wheelPrecision = 3.0;
  38655. /**
  38656. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  38657. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  38658. */
  38659. this.wheelDeltaPercentage = 0;
  38660. }
  38661. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  38662. var _this = this;
  38663. this._wheel = function (p, s) {
  38664. //sanity check - this should be a PointerWheel event.
  38665. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  38666. return;
  38667. var event = p.event;
  38668. var delta = 0;
  38669. if (event.wheelDelta) {
  38670. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  38671. }
  38672. else if (event.detail) {
  38673. delta = -event.detail / _this.wheelPrecision;
  38674. }
  38675. if (delta)
  38676. _this.camera.inertialRadiusOffset += delta;
  38677. if (event.preventDefault) {
  38678. if (!noPreventDefault) {
  38679. event.preventDefault();
  38680. }
  38681. }
  38682. };
  38683. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  38684. };
  38685. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  38686. if (this._observer && element) {
  38687. this.camera.getScene().onPointerObservable.remove(this._observer);
  38688. this._observer = null;
  38689. this._wheel = null;
  38690. }
  38691. };
  38692. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  38693. return "ArcRotateCameraMouseWheelInput";
  38694. };
  38695. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  38696. return "mousewheel";
  38697. };
  38698. __decorate([
  38699. BABYLON.serialize()
  38700. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  38701. __decorate([
  38702. BABYLON.serialize()
  38703. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  38704. return ArcRotateCameraMouseWheelInput;
  38705. }());
  38706. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  38707. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  38708. })(BABYLON || (BABYLON = {}));
  38709. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  38710. var BABYLON;
  38711. (function (BABYLON) {
  38712. var ArcRotateCameraPointersInput = /** @class */ (function () {
  38713. function ArcRotateCameraPointersInput() {
  38714. this.buttons = [0, 1, 2];
  38715. this.angularSensibilityX = 1000.0;
  38716. this.angularSensibilityY = 1000.0;
  38717. this.pinchPrecision = 12.0;
  38718. /**
  38719. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  38720. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  38721. */
  38722. this.pinchDeltaPercentage = 0;
  38723. this.panningSensibility = 1000.0;
  38724. this.multiTouchPanning = true;
  38725. this.multiTouchPanAndZoom = true;
  38726. this._isPanClick = false;
  38727. this.pinchInwards = true;
  38728. }
  38729. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  38730. var _this = this;
  38731. var engine = this.camera.getEngine();
  38732. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  38733. var pointA = null;
  38734. var pointB = null;
  38735. var previousPinchSquaredDistance = 0;
  38736. var initialDistance = 0;
  38737. var twoFingerActivityCount = 0;
  38738. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  38739. this._pointerInput = function (p, s) {
  38740. var evt = p.event;
  38741. var isTouch = p.event.pointerType === "touch";
  38742. if (engine.isInVRExclusivePointerMode) {
  38743. return;
  38744. }
  38745. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  38746. return;
  38747. }
  38748. var srcElement = (evt.srcElement || evt.target);
  38749. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  38750. try {
  38751. srcElement.setPointerCapture(evt.pointerId);
  38752. }
  38753. catch (e) {
  38754. //Nothing to do with the error. Execution will continue.
  38755. }
  38756. // Manage panning with pan button click
  38757. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  38758. // manage pointers
  38759. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  38760. if (pointA === null) {
  38761. pointA = cacheSoloPointer;
  38762. }
  38763. else if (pointB === null) {
  38764. pointB = cacheSoloPointer;
  38765. }
  38766. if (!noPreventDefault) {
  38767. evt.preventDefault();
  38768. element.focus();
  38769. }
  38770. }
  38771. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  38772. _this.camera.restoreState();
  38773. }
  38774. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  38775. try {
  38776. srcElement.releasePointerCapture(evt.pointerId);
  38777. }
  38778. catch (e) {
  38779. //Nothing to do with the error.
  38780. }
  38781. cacheSoloPointer = null;
  38782. previousPinchSquaredDistance = 0;
  38783. previousMultiTouchPanPosition.isPaning = false;
  38784. previousMultiTouchPanPosition.isPinching = false;
  38785. twoFingerActivityCount = 0;
  38786. initialDistance = 0;
  38787. if (!isTouch) {
  38788. pointB = null; // Mouse and pen are mono pointer
  38789. }
  38790. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  38791. //but emptying completly pointers collection is required to fix a bug on iPhone :
  38792. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  38793. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  38794. if (engine.badOS) {
  38795. pointA = pointB = null;
  38796. }
  38797. else {
  38798. //only remove the impacted pointer in case of multitouch allowing on most
  38799. //platforms switching from rotate to zoom and pan seamlessly.
  38800. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  38801. pointA = pointB;
  38802. pointB = null;
  38803. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  38804. }
  38805. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  38806. pointB = null;
  38807. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  38808. }
  38809. else {
  38810. pointA = pointB = null;
  38811. }
  38812. }
  38813. if (!noPreventDefault) {
  38814. evt.preventDefault();
  38815. }
  38816. }
  38817. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  38818. if (!noPreventDefault) {
  38819. evt.preventDefault();
  38820. }
  38821. // One button down
  38822. if (pointA && pointB === null && cacheSoloPointer) {
  38823. if (_this.panningSensibility !== 0 &&
  38824. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  38825. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  38826. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  38827. }
  38828. else {
  38829. var offsetX = evt.clientX - cacheSoloPointer.x;
  38830. var offsetY = evt.clientY - cacheSoloPointer.y;
  38831. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  38832. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  38833. }
  38834. cacheSoloPointer.x = evt.clientX;
  38835. cacheSoloPointer.y = evt.clientY;
  38836. }
  38837. else if (pointA && pointB) {
  38838. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  38839. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  38840. ed.x = evt.clientX;
  38841. ed.y = evt.clientY;
  38842. var direction = _this.pinchInwards ? 1 : -1;
  38843. var distX = pointA.x - pointB.x;
  38844. var distY = pointA.y - pointB.y;
  38845. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  38846. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  38847. if (previousPinchSquaredDistance === 0) {
  38848. initialDistance = pinchDistance;
  38849. previousPinchSquaredDistance = pinchSquaredDistance;
  38850. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  38851. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  38852. return;
  38853. }
  38854. if (_this.multiTouchPanAndZoom) {
  38855. if (_this.pinchDeltaPercentage) {
  38856. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  38857. }
  38858. else {
  38859. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  38860. (_this.pinchPrecision *
  38861. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  38862. direction);
  38863. }
  38864. if (_this.panningSensibility !== 0) {
  38865. var pointersCenterX = (pointA.x + pointB.x) / 2;
  38866. var pointersCenterY = (pointA.y + pointB.y) / 2;
  38867. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  38868. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  38869. previousMultiTouchPanPosition.x = pointersCenterX;
  38870. previousMultiTouchPanPosition.y = pointersCenterY;
  38871. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  38872. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  38873. }
  38874. }
  38875. else {
  38876. twoFingerActivityCount++;
  38877. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  38878. if (_this.pinchDeltaPercentage) {
  38879. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  38880. }
  38881. else {
  38882. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  38883. (_this.pinchPrecision *
  38884. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  38885. direction);
  38886. }
  38887. previousMultiTouchPanPosition.isPaning = false;
  38888. previousMultiTouchPanPosition.isPinching = true;
  38889. }
  38890. else {
  38891. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  38892. if (!previousMultiTouchPanPosition.isPaning) {
  38893. previousMultiTouchPanPosition.isPaning = true;
  38894. previousMultiTouchPanPosition.isPinching = false;
  38895. previousMultiTouchPanPosition.x = ed.x;
  38896. previousMultiTouchPanPosition.y = ed.y;
  38897. return;
  38898. }
  38899. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  38900. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  38901. }
  38902. }
  38903. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  38904. previousMultiTouchPanPosition.x = ed.x;
  38905. previousMultiTouchPanPosition.y = ed.y;
  38906. }
  38907. }
  38908. previousPinchSquaredDistance = pinchSquaredDistance;
  38909. }
  38910. }
  38911. };
  38912. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  38913. this._onContextMenu = function (evt) {
  38914. evt.preventDefault();
  38915. };
  38916. if (!this.camera._useCtrlForPanning) {
  38917. element.addEventListener("contextmenu", this._onContextMenu, false);
  38918. }
  38919. this._onLostFocus = function () {
  38920. //this._keys = [];
  38921. pointA = pointB = null;
  38922. previousPinchSquaredDistance = 0;
  38923. previousMultiTouchPanPosition.isPaning = false;
  38924. previousMultiTouchPanPosition.isPinching = false;
  38925. twoFingerActivityCount = 0;
  38926. cacheSoloPointer = null;
  38927. initialDistance = 0;
  38928. };
  38929. this._onMouseMove = function (evt) {
  38930. if (!engine.isPointerLock) {
  38931. return;
  38932. }
  38933. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  38934. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  38935. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  38936. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  38937. if (!noPreventDefault) {
  38938. evt.preventDefault();
  38939. }
  38940. };
  38941. this._onGestureStart = function (e) {
  38942. if (window.MSGesture === undefined) {
  38943. return;
  38944. }
  38945. if (!_this._MSGestureHandler) {
  38946. _this._MSGestureHandler = new MSGesture();
  38947. _this._MSGestureHandler.target = element;
  38948. }
  38949. _this._MSGestureHandler.addPointer(e.pointerId);
  38950. };
  38951. this._onGesture = function (e) {
  38952. _this.camera.radius *= e.scale;
  38953. if (e.preventDefault) {
  38954. if (!noPreventDefault) {
  38955. e.stopPropagation();
  38956. e.preventDefault();
  38957. }
  38958. }
  38959. };
  38960. element.addEventListener("mousemove", this._onMouseMove, false);
  38961. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  38962. element.addEventListener("MSGestureChange", this._onGesture, false);
  38963. BABYLON.Tools.RegisterTopRootEvents([
  38964. { name: "blur", handler: this._onLostFocus }
  38965. ]);
  38966. };
  38967. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  38968. if (this._onLostFocus) {
  38969. BABYLON.Tools.UnregisterTopRootEvents([
  38970. { name: "blur", handler: this._onLostFocus }
  38971. ]);
  38972. }
  38973. if (element && this._observer) {
  38974. this.camera.getScene().onPointerObservable.remove(this._observer);
  38975. this._observer = null;
  38976. if (this._onContextMenu) {
  38977. element.removeEventListener("contextmenu", this._onContextMenu);
  38978. }
  38979. if (this._onMouseMove) {
  38980. element.removeEventListener("mousemove", this._onMouseMove);
  38981. }
  38982. if (this._onGestureStart) {
  38983. element.removeEventListener("MSPointerDown", this._onGestureStart);
  38984. }
  38985. if (this._onGesture) {
  38986. element.removeEventListener("MSGestureChange", this._onGesture);
  38987. }
  38988. this._isPanClick = false;
  38989. this.pinchInwards = true;
  38990. this._onMouseMove = null;
  38991. this._onGestureStart = null;
  38992. this._onGesture = null;
  38993. this._MSGestureHandler = null;
  38994. this._onLostFocus = null;
  38995. this._onContextMenu = null;
  38996. }
  38997. };
  38998. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  38999. return "ArcRotateCameraPointersInput";
  39000. };
  39001. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  39002. return "pointers";
  39003. };
  39004. __decorate([
  39005. BABYLON.serialize()
  39006. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  39007. __decorate([
  39008. BABYLON.serialize()
  39009. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  39010. __decorate([
  39011. BABYLON.serialize()
  39012. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  39013. __decorate([
  39014. BABYLON.serialize()
  39015. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  39016. __decorate([
  39017. BABYLON.serialize()
  39018. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  39019. __decorate([
  39020. BABYLON.serialize()
  39021. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  39022. __decorate([
  39023. BABYLON.serialize()
  39024. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  39025. __decorate([
  39026. BABYLON.serialize()
  39027. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  39028. return ArcRotateCameraPointersInput;
  39029. }());
  39030. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  39031. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  39032. })(BABYLON || (BABYLON = {}));
  39033. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  39034. var BABYLON;
  39035. (function (BABYLON) {
  39036. var ArcRotateCamera = /** @class */ (function (_super) {
  39037. __extends(ArcRotateCamera, _super);
  39038. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  39039. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  39040. _this.inertialAlphaOffset = 0;
  39041. _this.inertialBetaOffset = 0;
  39042. _this.inertialRadiusOffset = 0;
  39043. _this.lowerAlphaLimit = null;
  39044. _this.upperAlphaLimit = null;
  39045. _this.lowerBetaLimit = 0.01;
  39046. _this.upperBetaLimit = Math.PI;
  39047. _this.lowerRadiusLimit = null;
  39048. _this.upperRadiusLimit = null;
  39049. _this.inertialPanningX = 0;
  39050. _this.inertialPanningY = 0;
  39051. _this.pinchToPanMaxDistance = 20;
  39052. _this.panningDistanceLimit = null;
  39053. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  39054. _this.panningInertia = 0.9;
  39055. //-- end properties for backward compatibility for inputs
  39056. _this.zoomOnFactor = 1;
  39057. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  39058. _this.allowUpsideDown = true;
  39059. _this._viewMatrix = new BABYLON.Matrix();
  39060. // Panning
  39061. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  39062. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  39063. _this.checkCollisions = false;
  39064. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  39065. _this._previousPosition = BABYLON.Vector3.Zero();
  39066. _this._collisionVelocity = BABYLON.Vector3.Zero();
  39067. _this._newPosition = BABYLON.Vector3.Zero();
  39068. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  39069. if (collidedMesh === void 0) { collidedMesh = null; }
  39070. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  39071. newPosition.multiplyInPlace(_this._collider.radius);
  39072. }
  39073. if (!collidedMesh) {
  39074. _this._previousPosition.copyFrom(_this.position);
  39075. }
  39076. else {
  39077. _this.setPosition(newPosition);
  39078. if (_this.onCollide) {
  39079. _this.onCollide(collidedMesh);
  39080. }
  39081. }
  39082. // Recompute because of constraints
  39083. var cosa = Math.cos(_this.alpha);
  39084. var sina = Math.sin(_this.alpha);
  39085. var cosb = Math.cos(_this.beta);
  39086. var sinb = Math.sin(_this.beta);
  39087. if (sinb === 0) {
  39088. sinb = 0.0001;
  39089. }
  39090. var target = _this._getTargetPosition();
  39091. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  39092. _this.position.copyFrom(_this._newPosition);
  39093. var up = _this.upVector;
  39094. if (_this.allowUpsideDown && _this.beta < 0) {
  39095. up = up.clone();
  39096. up = up.negate();
  39097. }
  39098. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  39099. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  39100. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  39101. _this._collisionTriggered = false;
  39102. };
  39103. _this._target = BABYLON.Vector3.Zero();
  39104. if (target) {
  39105. _this.setTarget(target);
  39106. }
  39107. _this.alpha = alpha;
  39108. _this.beta = beta;
  39109. _this.radius = radius;
  39110. _this.getViewMatrix();
  39111. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  39112. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  39113. return _this;
  39114. }
  39115. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  39116. get: function () {
  39117. return this._target;
  39118. },
  39119. set: function (value) {
  39120. this.setTarget(value);
  39121. },
  39122. enumerable: true,
  39123. configurable: true
  39124. });
  39125. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  39126. //-- begin properties for backward compatibility for inputs
  39127. get: function () {
  39128. var pointers = this.inputs.attached["pointers"];
  39129. if (pointers)
  39130. return pointers.angularSensibilityX;
  39131. return 0;
  39132. },
  39133. set: function (value) {
  39134. var pointers = this.inputs.attached["pointers"];
  39135. if (pointers) {
  39136. pointers.angularSensibilityX = value;
  39137. }
  39138. },
  39139. enumerable: true,
  39140. configurable: true
  39141. });
  39142. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  39143. get: function () {
  39144. var pointers = this.inputs.attached["pointers"];
  39145. if (pointers)
  39146. return pointers.angularSensibilityY;
  39147. return 0;
  39148. },
  39149. set: function (value) {
  39150. var pointers = this.inputs.attached["pointers"];
  39151. if (pointers) {
  39152. pointers.angularSensibilityY = value;
  39153. }
  39154. },
  39155. enumerable: true,
  39156. configurable: true
  39157. });
  39158. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  39159. get: function () {
  39160. var pointers = this.inputs.attached["pointers"];
  39161. if (pointers)
  39162. return pointers.pinchPrecision;
  39163. return 0;
  39164. },
  39165. set: function (value) {
  39166. var pointers = this.inputs.attached["pointers"];
  39167. if (pointers) {
  39168. pointers.pinchPrecision = value;
  39169. }
  39170. },
  39171. enumerable: true,
  39172. configurable: true
  39173. });
  39174. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  39175. get: function () {
  39176. var pointers = this.inputs.attached["pointers"];
  39177. if (pointers)
  39178. return pointers.pinchDeltaPercentage;
  39179. return 0;
  39180. },
  39181. set: function (value) {
  39182. var pointers = this.inputs.attached["pointers"];
  39183. if (pointers) {
  39184. pointers.pinchDeltaPercentage = value;
  39185. }
  39186. },
  39187. enumerable: true,
  39188. configurable: true
  39189. });
  39190. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  39191. get: function () {
  39192. var pointers = this.inputs.attached["pointers"];
  39193. if (pointers)
  39194. return pointers.panningSensibility;
  39195. return 0;
  39196. },
  39197. set: function (value) {
  39198. var pointers = this.inputs.attached["pointers"];
  39199. if (pointers) {
  39200. pointers.panningSensibility = value;
  39201. }
  39202. },
  39203. enumerable: true,
  39204. configurable: true
  39205. });
  39206. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  39207. get: function () {
  39208. var keyboard = this.inputs.attached["keyboard"];
  39209. if (keyboard)
  39210. return keyboard.keysUp;
  39211. return [];
  39212. },
  39213. set: function (value) {
  39214. var keyboard = this.inputs.attached["keyboard"];
  39215. if (keyboard)
  39216. keyboard.keysUp = value;
  39217. },
  39218. enumerable: true,
  39219. configurable: true
  39220. });
  39221. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  39222. get: function () {
  39223. var keyboard = this.inputs.attached["keyboard"];
  39224. if (keyboard)
  39225. return keyboard.keysDown;
  39226. return [];
  39227. },
  39228. set: function (value) {
  39229. var keyboard = this.inputs.attached["keyboard"];
  39230. if (keyboard)
  39231. keyboard.keysDown = value;
  39232. },
  39233. enumerable: true,
  39234. configurable: true
  39235. });
  39236. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  39237. get: function () {
  39238. var keyboard = this.inputs.attached["keyboard"];
  39239. if (keyboard)
  39240. return keyboard.keysLeft;
  39241. return [];
  39242. },
  39243. set: function (value) {
  39244. var keyboard = this.inputs.attached["keyboard"];
  39245. if (keyboard)
  39246. keyboard.keysLeft = value;
  39247. },
  39248. enumerable: true,
  39249. configurable: true
  39250. });
  39251. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  39252. get: function () {
  39253. var keyboard = this.inputs.attached["keyboard"];
  39254. if (keyboard)
  39255. return keyboard.keysRight;
  39256. return [];
  39257. },
  39258. set: function (value) {
  39259. var keyboard = this.inputs.attached["keyboard"];
  39260. if (keyboard)
  39261. keyboard.keysRight = value;
  39262. },
  39263. enumerable: true,
  39264. configurable: true
  39265. });
  39266. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  39267. get: function () {
  39268. var mousewheel = this.inputs.attached["mousewheel"];
  39269. if (mousewheel)
  39270. return mousewheel.wheelPrecision;
  39271. return 0;
  39272. },
  39273. set: function (value) {
  39274. var mousewheel = this.inputs.attached["mousewheel"];
  39275. if (mousewheel)
  39276. mousewheel.wheelPrecision = value;
  39277. },
  39278. enumerable: true,
  39279. configurable: true
  39280. });
  39281. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  39282. get: function () {
  39283. var mousewheel = this.inputs.attached["mousewheel"];
  39284. if (mousewheel)
  39285. return mousewheel.wheelDeltaPercentage;
  39286. return 0;
  39287. },
  39288. set: function (value) {
  39289. var mousewheel = this.inputs.attached["mousewheel"];
  39290. if (mousewheel)
  39291. mousewheel.wheelDeltaPercentage = value;
  39292. },
  39293. enumerable: true,
  39294. configurable: true
  39295. });
  39296. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  39297. get: function () {
  39298. return this._bouncingBehavior;
  39299. },
  39300. enumerable: true,
  39301. configurable: true
  39302. });
  39303. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  39304. get: function () {
  39305. return this._bouncingBehavior != null;
  39306. },
  39307. set: function (value) {
  39308. if (value === this.useBouncingBehavior) {
  39309. return;
  39310. }
  39311. if (value) {
  39312. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  39313. this.addBehavior(this._bouncingBehavior);
  39314. }
  39315. else if (this._bouncingBehavior) {
  39316. this.removeBehavior(this._bouncingBehavior);
  39317. this._bouncingBehavior = null;
  39318. }
  39319. },
  39320. enumerable: true,
  39321. configurable: true
  39322. });
  39323. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  39324. get: function () {
  39325. return this._framingBehavior;
  39326. },
  39327. enumerable: true,
  39328. configurable: true
  39329. });
  39330. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  39331. get: function () {
  39332. return this._framingBehavior != null;
  39333. },
  39334. set: function (value) {
  39335. if (value === this.useFramingBehavior) {
  39336. return;
  39337. }
  39338. if (value) {
  39339. this._framingBehavior = new BABYLON.FramingBehavior();
  39340. this.addBehavior(this._framingBehavior);
  39341. }
  39342. else if (this._framingBehavior) {
  39343. this.removeBehavior(this._framingBehavior);
  39344. this._framingBehavior = null;
  39345. }
  39346. },
  39347. enumerable: true,
  39348. configurable: true
  39349. });
  39350. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  39351. get: function () {
  39352. return this._autoRotationBehavior;
  39353. },
  39354. enumerable: true,
  39355. configurable: true
  39356. });
  39357. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  39358. get: function () {
  39359. return this._autoRotationBehavior != null;
  39360. },
  39361. set: function (value) {
  39362. if (value === this.useAutoRotationBehavior) {
  39363. return;
  39364. }
  39365. if (value) {
  39366. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  39367. this.addBehavior(this._autoRotationBehavior);
  39368. }
  39369. else if (this._autoRotationBehavior) {
  39370. this.removeBehavior(this._autoRotationBehavior);
  39371. this._autoRotationBehavior = null;
  39372. }
  39373. },
  39374. enumerable: true,
  39375. configurable: true
  39376. });
  39377. // Cache
  39378. ArcRotateCamera.prototype._initCache = function () {
  39379. _super.prototype._initCache.call(this);
  39380. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39381. this._cache.alpha = undefined;
  39382. this._cache.beta = undefined;
  39383. this._cache.radius = undefined;
  39384. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  39385. };
  39386. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  39387. if (!ignoreParentClass) {
  39388. _super.prototype._updateCache.call(this);
  39389. }
  39390. this._cache._target.copyFrom(this._getTargetPosition());
  39391. this._cache.alpha = this.alpha;
  39392. this._cache.beta = this.beta;
  39393. this._cache.radius = this.radius;
  39394. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  39395. };
  39396. ArcRotateCamera.prototype._getTargetPosition = function () {
  39397. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  39398. var pos = this._targetHost.getAbsolutePosition();
  39399. if (this._targetBoundingCenter) {
  39400. pos.addToRef(this._targetBoundingCenter, this._target);
  39401. }
  39402. else {
  39403. this._target.copyFrom(pos);
  39404. }
  39405. }
  39406. var lockedTargetPosition = this._getLockedTargetPosition();
  39407. if (lockedTargetPosition) {
  39408. return lockedTargetPosition;
  39409. }
  39410. return this._target;
  39411. };
  39412. ArcRotateCamera.prototype.storeState = function () {
  39413. this._storedAlpha = this.alpha;
  39414. this._storedBeta = this.beta;
  39415. this._storedRadius = this.radius;
  39416. this._storedTarget = this._getTargetPosition().clone();
  39417. return _super.prototype.storeState.call(this);
  39418. };
  39419. /**
  39420. * Restored camera state. You must call storeState() first
  39421. */
  39422. ArcRotateCamera.prototype._restoreStateValues = function () {
  39423. if (!_super.prototype._restoreStateValues.call(this)) {
  39424. return false;
  39425. }
  39426. this.alpha = this._storedAlpha;
  39427. this.beta = this._storedBeta;
  39428. this.radius = this._storedRadius;
  39429. this.setTarget(this._storedTarget.clone());
  39430. this.inertialAlphaOffset = 0;
  39431. this.inertialBetaOffset = 0;
  39432. this.inertialRadiusOffset = 0;
  39433. this.inertialPanningX = 0;
  39434. this.inertialPanningY = 0;
  39435. return true;
  39436. };
  39437. // Synchronized
  39438. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  39439. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  39440. return false;
  39441. return this._cache._target.equals(this._getTargetPosition())
  39442. && this._cache.alpha === this.alpha
  39443. && this._cache.beta === this.beta
  39444. && this._cache.radius === this.radius
  39445. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  39446. };
  39447. // Methods
  39448. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  39449. var _this = this;
  39450. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  39451. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  39452. this._useCtrlForPanning = useCtrlForPanning;
  39453. this._panningMouseButton = panningMouseButton;
  39454. this.inputs.attachElement(element, noPreventDefault);
  39455. this._reset = function () {
  39456. _this.inertialAlphaOffset = 0;
  39457. _this.inertialBetaOffset = 0;
  39458. _this.inertialRadiusOffset = 0;
  39459. _this.inertialPanningX = 0;
  39460. _this.inertialPanningY = 0;
  39461. };
  39462. };
  39463. ArcRotateCamera.prototype.detachControl = function (element) {
  39464. this.inputs.detachElement(element);
  39465. if (this._reset) {
  39466. this._reset();
  39467. }
  39468. };
  39469. ArcRotateCamera.prototype._checkInputs = function () {
  39470. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  39471. if (this._collisionTriggered) {
  39472. return;
  39473. }
  39474. this.inputs.checkInputs();
  39475. // Inertia
  39476. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  39477. if (this.getScene().useRightHandedSystem) {
  39478. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  39479. }
  39480. else {
  39481. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  39482. }
  39483. this.beta += this.inertialBetaOffset;
  39484. this.radius -= this.inertialRadiusOffset;
  39485. this.inertialAlphaOffset *= this.inertia;
  39486. this.inertialBetaOffset *= this.inertia;
  39487. this.inertialRadiusOffset *= this.inertia;
  39488. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  39489. this.inertialAlphaOffset = 0;
  39490. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  39491. this.inertialBetaOffset = 0;
  39492. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  39493. this.inertialRadiusOffset = 0;
  39494. }
  39495. // Panning inertia
  39496. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  39497. if (!this._localDirection) {
  39498. this._localDirection = BABYLON.Vector3.Zero();
  39499. this._transformedDirection = BABYLON.Vector3.Zero();
  39500. }
  39501. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  39502. this._localDirection.multiplyInPlace(this.panningAxis);
  39503. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  39504. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  39505. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  39506. if (!this.panningAxis.y) {
  39507. this._transformedDirection.y = 0;
  39508. }
  39509. if (!this._targetHost) {
  39510. if (this.panningDistanceLimit) {
  39511. this._transformedDirection.addInPlace(this._target);
  39512. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  39513. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  39514. this._target.copyFrom(this._transformedDirection);
  39515. }
  39516. }
  39517. else {
  39518. this._target.addInPlace(this._transformedDirection);
  39519. }
  39520. }
  39521. this.inertialPanningX *= this.panningInertia;
  39522. this.inertialPanningY *= this.panningInertia;
  39523. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  39524. this.inertialPanningX = 0;
  39525. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  39526. this.inertialPanningY = 0;
  39527. }
  39528. // Limits
  39529. this._checkLimits();
  39530. _super.prototype._checkInputs.call(this);
  39531. };
  39532. ArcRotateCamera.prototype._checkLimits = function () {
  39533. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  39534. if (this.allowUpsideDown && this.beta > Math.PI) {
  39535. this.beta = this.beta - (2 * Math.PI);
  39536. }
  39537. }
  39538. else {
  39539. if (this.beta < this.lowerBetaLimit) {
  39540. this.beta = this.lowerBetaLimit;
  39541. }
  39542. }
  39543. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  39544. if (this.allowUpsideDown && this.beta < -Math.PI) {
  39545. this.beta = this.beta + (2 * Math.PI);
  39546. }
  39547. }
  39548. else {
  39549. if (this.beta > this.upperBetaLimit) {
  39550. this.beta = this.upperBetaLimit;
  39551. }
  39552. }
  39553. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  39554. this.alpha = this.lowerAlphaLimit;
  39555. }
  39556. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  39557. this.alpha = this.upperAlphaLimit;
  39558. }
  39559. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  39560. this.radius = this.lowerRadiusLimit;
  39561. }
  39562. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  39563. this.radius = this.upperRadiusLimit;
  39564. }
  39565. };
  39566. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  39567. var radiusv3 = this.position.subtract(this._getTargetPosition());
  39568. this.radius = radiusv3.length();
  39569. if (this.radius === 0) {
  39570. this.radius = 0.0001; // Just to avoid division by zero
  39571. }
  39572. // Alpha
  39573. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  39574. if (radiusv3.z < 0) {
  39575. this.alpha = 2 * Math.PI - this.alpha;
  39576. }
  39577. // Beta
  39578. this.beta = Math.acos(radiusv3.y / this.radius);
  39579. this._checkLimits();
  39580. };
  39581. ArcRotateCamera.prototype.setPosition = function (position) {
  39582. if (this.position.equals(position)) {
  39583. return;
  39584. }
  39585. this.position.copyFrom(position);
  39586. this.rebuildAnglesAndRadius();
  39587. };
  39588. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  39589. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  39590. if (allowSamePosition === void 0) { allowSamePosition = false; }
  39591. if (target.getBoundingInfo) {
  39592. if (toBoundingCenter) {
  39593. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  39594. }
  39595. else {
  39596. this._targetBoundingCenter = null;
  39597. }
  39598. this._targetHost = target;
  39599. this._target = this._getTargetPosition();
  39600. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  39601. }
  39602. else {
  39603. var newTarget = target;
  39604. var currentTarget = this._getTargetPosition();
  39605. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  39606. return;
  39607. }
  39608. this._targetHost = null;
  39609. this._target = newTarget;
  39610. this._targetBoundingCenter = null;
  39611. this.onMeshTargetChangedObservable.notifyObservers(null);
  39612. }
  39613. this.rebuildAnglesAndRadius();
  39614. };
  39615. ArcRotateCamera.prototype._getViewMatrix = function () {
  39616. // Compute
  39617. var cosa = Math.cos(this.alpha);
  39618. var sina = Math.sin(this.alpha);
  39619. var cosb = Math.cos(this.beta);
  39620. var sinb = Math.sin(this.beta);
  39621. if (sinb === 0) {
  39622. sinb = 0.0001;
  39623. }
  39624. var target = this._getTargetPosition();
  39625. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  39626. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  39627. if (!this._collider) {
  39628. this._collider = new BABYLON.Collider();
  39629. }
  39630. this._collider.radius = this.collisionRadius;
  39631. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  39632. this._collisionTriggered = true;
  39633. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  39634. }
  39635. else {
  39636. this.position.copyFrom(this._newPosition);
  39637. var up = this.upVector;
  39638. if (this.allowUpsideDown && sinb < 0) {
  39639. up = up.clone();
  39640. up = up.negate();
  39641. }
  39642. if (this.getScene().useRightHandedSystem) {
  39643. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  39644. }
  39645. else {
  39646. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  39647. }
  39648. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  39649. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  39650. }
  39651. this._currentTarget = target;
  39652. return this._viewMatrix;
  39653. };
  39654. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  39655. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  39656. meshes = meshes || this.getScene().meshes;
  39657. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  39658. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  39659. this.radius = distance * this.zoomOnFactor;
  39660. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  39661. };
  39662. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  39663. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  39664. var meshesOrMinMaxVector;
  39665. var distance;
  39666. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  39667. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  39668. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  39669. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  39670. }
  39671. else {
  39672. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  39673. meshesOrMinMaxVector = minMaxVectorAndDistance;
  39674. distance = minMaxVectorAndDistance.distance;
  39675. }
  39676. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  39677. if (!doNotUpdateMaxZ) {
  39678. this.maxZ = distance * 2;
  39679. }
  39680. };
  39681. /**
  39682. * @override
  39683. * Override Camera.createRigCamera
  39684. */
  39685. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  39686. var alphaShift = 0;
  39687. switch (this.cameraRigMode) {
  39688. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39689. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39690. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39691. case BABYLON.Camera.RIG_MODE_VR:
  39692. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  39693. break;
  39694. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39695. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  39696. break;
  39697. }
  39698. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  39699. rigCam._cameraRigParams = {};
  39700. return rigCam;
  39701. };
  39702. /**
  39703. * @override
  39704. * Override Camera._updateRigCameras
  39705. */
  39706. ArcRotateCamera.prototype._updateRigCameras = function () {
  39707. var camLeft = this._rigCameras[0];
  39708. var camRight = this._rigCameras[1];
  39709. camLeft.beta = camRight.beta = this.beta;
  39710. camLeft.radius = camRight.radius = this.radius;
  39711. switch (this.cameraRigMode) {
  39712. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39713. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39714. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39715. case BABYLON.Camera.RIG_MODE_VR:
  39716. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  39717. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  39718. break;
  39719. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39720. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  39721. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  39722. break;
  39723. }
  39724. _super.prototype._updateRigCameras.call(this);
  39725. };
  39726. ArcRotateCamera.prototype.dispose = function () {
  39727. this.inputs.clear();
  39728. _super.prototype.dispose.call(this);
  39729. };
  39730. ArcRotateCamera.prototype.getClassName = function () {
  39731. return "ArcRotateCamera";
  39732. };
  39733. __decorate([
  39734. BABYLON.serialize()
  39735. ], ArcRotateCamera.prototype, "alpha", void 0);
  39736. __decorate([
  39737. BABYLON.serialize()
  39738. ], ArcRotateCamera.prototype, "beta", void 0);
  39739. __decorate([
  39740. BABYLON.serialize()
  39741. ], ArcRotateCamera.prototype, "radius", void 0);
  39742. __decorate([
  39743. BABYLON.serializeAsVector3("target")
  39744. ], ArcRotateCamera.prototype, "_target", void 0);
  39745. __decorate([
  39746. BABYLON.serialize()
  39747. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  39748. __decorate([
  39749. BABYLON.serialize()
  39750. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  39751. __decorate([
  39752. BABYLON.serialize()
  39753. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  39754. __decorate([
  39755. BABYLON.serialize()
  39756. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  39757. __decorate([
  39758. BABYLON.serialize()
  39759. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  39760. __decorate([
  39761. BABYLON.serialize()
  39762. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  39763. __decorate([
  39764. BABYLON.serialize()
  39765. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  39766. __decorate([
  39767. BABYLON.serialize()
  39768. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  39769. __decorate([
  39770. BABYLON.serialize()
  39771. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  39772. __decorate([
  39773. BABYLON.serialize()
  39774. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  39775. __decorate([
  39776. BABYLON.serialize()
  39777. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  39778. __decorate([
  39779. BABYLON.serialize()
  39780. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  39781. __decorate([
  39782. BABYLON.serialize()
  39783. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  39784. __decorate([
  39785. BABYLON.serializeAsVector3()
  39786. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  39787. __decorate([
  39788. BABYLON.serialize()
  39789. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  39790. __decorate([
  39791. BABYLON.serialize()
  39792. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  39793. __decorate([
  39794. BABYLON.serialize()
  39795. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  39796. return ArcRotateCamera;
  39797. }(BABYLON.TargetCamera));
  39798. BABYLON.ArcRotateCamera = ArcRotateCamera;
  39799. })(BABYLON || (BABYLON = {}));
  39800. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  39801. var BABYLON;
  39802. (function (BABYLON) {
  39803. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  39804. __extends(ArcRotateCameraInputsManager, _super);
  39805. function ArcRotateCameraInputsManager(camera) {
  39806. return _super.call(this, camera) || this;
  39807. }
  39808. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  39809. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  39810. return this;
  39811. };
  39812. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  39813. this.add(new BABYLON.ArcRotateCameraPointersInput());
  39814. return this;
  39815. };
  39816. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  39817. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  39818. return this;
  39819. };
  39820. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  39821. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  39822. return this;
  39823. };
  39824. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  39825. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  39826. return this;
  39827. };
  39828. return ArcRotateCameraInputsManager;
  39829. }(BABYLON.CameraInputsManager));
  39830. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  39831. })(BABYLON || (BABYLON = {}));
  39832. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  39833. var BABYLON;
  39834. (function (BABYLON) {
  39835. var HemisphericLight = /** @class */ (function (_super) {
  39836. __extends(HemisphericLight, _super);
  39837. /**
  39838. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  39839. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  39840. * The HemisphericLight can't cast shadows.
  39841. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39842. */
  39843. function HemisphericLight(name, direction, scene) {
  39844. var _this = _super.call(this, name, scene) || this;
  39845. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  39846. _this.direction = direction || BABYLON.Vector3.Up();
  39847. return _this;
  39848. }
  39849. HemisphericLight.prototype._buildUniformLayout = function () {
  39850. this._uniformBuffer.addUniform("vLightData", 4);
  39851. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39852. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39853. this._uniformBuffer.addUniform("vLightGround", 3);
  39854. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39855. this._uniformBuffer.addUniform("depthValues", 2);
  39856. this._uniformBuffer.create();
  39857. };
  39858. /**
  39859. * Returns the string "HemisphericLight".
  39860. */
  39861. HemisphericLight.prototype.getClassName = function () {
  39862. return "HemisphericLight";
  39863. };
  39864. /**
  39865. * Sets the HemisphericLight direction towards the passed target (Vector3).
  39866. * Returns the updated direction.
  39867. */
  39868. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  39869. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  39870. return this.direction;
  39871. };
  39872. HemisphericLight.prototype.getShadowGenerator = function () {
  39873. return null;
  39874. };
  39875. /**
  39876. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  39877. * Returns the HemisphericLight.
  39878. */
  39879. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  39880. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  39881. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  39882. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  39883. return this;
  39884. };
  39885. HemisphericLight.prototype._getWorldMatrix = function () {
  39886. if (!this._worldMatrix) {
  39887. this._worldMatrix = BABYLON.Matrix.Identity();
  39888. }
  39889. return this._worldMatrix;
  39890. };
  39891. /**
  39892. * Returns the integer 3.
  39893. */
  39894. HemisphericLight.prototype.getTypeID = function () {
  39895. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  39896. };
  39897. __decorate([
  39898. BABYLON.serializeAsColor3()
  39899. ], HemisphericLight.prototype, "groundColor", void 0);
  39900. __decorate([
  39901. BABYLON.serializeAsVector3()
  39902. ], HemisphericLight.prototype, "direction", void 0);
  39903. return HemisphericLight;
  39904. }(BABYLON.Light));
  39905. BABYLON.HemisphericLight = HemisphericLight;
  39906. })(BABYLON || (BABYLON = {}));
  39907. //# sourceMappingURL=babylon.hemisphericLight.js.map
  39908. var BABYLON;
  39909. (function (BABYLON) {
  39910. var ShadowLight = /** @class */ (function (_super) {
  39911. __extends(ShadowLight, _super);
  39912. function ShadowLight() {
  39913. var _this = _super !== null && _super.apply(this, arguments) || this;
  39914. _this._needProjectionMatrixCompute = true;
  39915. return _this;
  39916. }
  39917. Object.defineProperty(ShadowLight.prototype, "direction", {
  39918. get: function () {
  39919. return this._direction;
  39920. },
  39921. set: function (value) {
  39922. this._direction = value;
  39923. },
  39924. enumerable: true,
  39925. configurable: true
  39926. });
  39927. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  39928. get: function () {
  39929. return this._shadowMinZ;
  39930. },
  39931. set: function (value) {
  39932. this._shadowMinZ = value;
  39933. this.forceProjectionMatrixCompute();
  39934. },
  39935. enumerable: true,
  39936. configurable: true
  39937. });
  39938. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  39939. get: function () {
  39940. return this._shadowMaxZ;
  39941. },
  39942. set: function (value) {
  39943. this._shadowMaxZ = value;
  39944. this.forceProjectionMatrixCompute();
  39945. },
  39946. enumerable: true,
  39947. configurable: true
  39948. });
  39949. /**
  39950. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  39951. */
  39952. ShadowLight.prototype.computeTransformedInformation = function () {
  39953. if (this.parent && this.parent.getWorldMatrix) {
  39954. if (!this.transformedPosition) {
  39955. this.transformedPosition = BABYLON.Vector3.Zero();
  39956. }
  39957. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  39958. // In case the direction is present.
  39959. if (this.direction) {
  39960. if (!this.transformedDirection) {
  39961. this.transformedDirection = BABYLON.Vector3.Zero();
  39962. }
  39963. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  39964. }
  39965. return true;
  39966. }
  39967. return false;
  39968. };
  39969. /**
  39970. * Return the depth scale used for the shadow map.
  39971. */
  39972. ShadowLight.prototype.getDepthScale = function () {
  39973. return 50.0;
  39974. };
  39975. /**
  39976. * Returns the light direction (Vector3) for any passed face index.
  39977. */
  39978. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  39979. return this.transformedDirection ? this.transformedDirection : this.direction;
  39980. };
  39981. /**
  39982. * Returns the DirectionalLight absolute position in the World.
  39983. */
  39984. ShadowLight.prototype.getAbsolutePosition = function () {
  39985. return this.transformedPosition ? this.transformedPosition : this.position;
  39986. };
  39987. /**
  39988. * Sets the DirectionalLight direction toward the passed target (Vector3).
  39989. * Returns the updated DirectionalLight direction (Vector3).
  39990. */
  39991. ShadowLight.prototype.setDirectionToTarget = function (target) {
  39992. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  39993. return this.direction;
  39994. };
  39995. /**
  39996. * Returns the light rotation (Vector3).
  39997. */
  39998. ShadowLight.prototype.getRotation = function () {
  39999. this.direction.normalize();
  40000. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  40001. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  40002. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  40003. };
  40004. /**
  40005. * Boolean : false by default.
  40006. */
  40007. ShadowLight.prototype.needCube = function () {
  40008. return false;
  40009. };
  40010. /**
  40011. * Specifies wether or not the projection matrix should be recomputed this frame.
  40012. */
  40013. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  40014. return this._needProjectionMatrixCompute;
  40015. };
  40016. /**
  40017. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  40018. */
  40019. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  40020. this._needProjectionMatrixCompute = true;
  40021. };
  40022. /**
  40023. * Get the world matrix of the sahdow lights.
  40024. */
  40025. ShadowLight.prototype._getWorldMatrix = function () {
  40026. if (!this._worldMatrix) {
  40027. this._worldMatrix = BABYLON.Matrix.Identity();
  40028. }
  40029. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  40030. return this._worldMatrix;
  40031. };
  40032. /**
  40033. * Gets the minZ used for shadow according to both the scene and the light.
  40034. * @param activeCamera
  40035. */
  40036. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  40037. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  40038. };
  40039. /**
  40040. * Gets the maxZ used for shadow according to both the scene and the light.
  40041. * @param activeCamera
  40042. */
  40043. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  40044. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  40045. };
  40046. /**
  40047. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  40048. * Returns the light.
  40049. */
  40050. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40051. if (this.customProjectionMatrixBuilder) {
  40052. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  40053. }
  40054. else {
  40055. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  40056. }
  40057. return this;
  40058. };
  40059. __decorate([
  40060. BABYLON.serializeAsVector3()
  40061. ], ShadowLight.prototype, "position", void 0);
  40062. __decorate([
  40063. BABYLON.serializeAsVector3()
  40064. ], ShadowLight.prototype, "direction", null);
  40065. __decorate([
  40066. BABYLON.serialize()
  40067. ], ShadowLight.prototype, "shadowMinZ", null);
  40068. __decorate([
  40069. BABYLON.serialize()
  40070. ], ShadowLight.prototype, "shadowMaxZ", null);
  40071. return ShadowLight;
  40072. }(BABYLON.Light));
  40073. BABYLON.ShadowLight = ShadowLight;
  40074. })(BABYLON || (BABYLON = {}));
  40075. //# sourceMappingURL=babylon.shadowLight.js.map
  40076. var BABYLON;
  40077. (function (BABYLON) {
  40078. var PointLight = /** @class */ (function (_super) {
  40079. __extends(PointLight, _super);
  40080. /**
  40081. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  40082. * A PointLight emits the light in every direction.
  40083. * It can cast shadows.
  40084. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  40085. * ```javascript
  40086. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  40087. * ```
  40088. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40089. */
  40090. function PointLight(name, position, scene) {
  40091. var _this = _super.call(this, name, scene) || this;
  40092. _this._shadowAngle = Math.PI / 2;
  40093. _this.position = position;
  40094. return _this;
  40095. }
  40096. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  40097. /**
  40098. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40099. * This specifies what angle the shadow will use to be created.
  40100. *
  40101. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  40102. */
  40103. get: function () {
  40104. return this._shadowAngle;
  40105. },
  40106. /**
  40107. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40108. * This specifies what angle the shadow will use to be created.
  40109. *
  40110. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  40111. */
  40112. set: function (value) {
  40113. this._shadowAngle = value;
  40114. this.forceProjectionMatrixCompute();
  40115. },
  40116. enumerable: true,
  40117. configurable: true
  40118. });
  40119. Object.defineProperty(PointLight.prototype, "direction", {
  40120. get: function () {
  40121. return this._direction;
  40122. },
  40123. /**
  40124. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40125. */
  40126. set: function (value) {
  40127. var previousNeedCube = this.needCube();
  40128. this._direction = value;
  40129. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  40130. this._shadowGenerator.recreateShadowMap();
  40131. }
  40132. },
  40133. enumerable: true,
  40134. configurable: true
  40135. });
  40136. /**
  40137. * Returns the string "PointLight"
  40138. */
  40139. PointLight.prototype.getClassName = function () {
  40140. return "PointLight";
  40141. };
  40142. /**
  40143. * Returns the integer 0.
  40144. */
  40145. PointLight.prototype.getTypeID = function () {
  40146. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  40147. };
  40148. /**
  40149. * Specifies wether or not the shadowmap should be a cube texture.
  40150. */
  40151. PointLight.prototype.needCube = function () {
  40152. return !this.direction;
  40153. };
  40154. /**
  40155. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  40156. */
  40157. PointLight.prototype.getShadowDirection = function (faceIndex) {
  40158. if (this.direction) {
  40159. return _super.prototype.getShadowDirection.call(this, faceIndex);
  40160. }
  40161. else {
  40162. switch (faceIndex) {
  40163. case 0:
  40164. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  40165. case 1:
  40166. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  40167. case 2:
  40168. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  40169. case 3:
  40170. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  40171. case 4:
  40172. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  40173. case 5:
  40174. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  40175. }
  40176. }
  40177. return BABYLON.Vector3.Zero();
  40178. };
  40179. /**
  40180. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  40181. * - fov = PI / 2
  40182. * - aspect ratio : 1.0
  40183. * - z-near and far equal to the active camera minZ and maxZ.
  40184. * Returns the PointLight.
  40185. */
  40186. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40187. var activeCamera = this.getScene().activeCamera;
  40188. if (!activeCamera) {
  40189. return;
  40190. }
  40191. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  40192. };
  40193. PointLight.prototype._buildUniformLayout = function () {
  40194. this._uniformBuffer.addUniform("vLightData", 4);
  40195. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40196. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40197. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40198. this._uniformBuffer.addUniform("depthValues", 2);
  40199. this._uniformBuffer.create();
  40200. };
  40201. /**
  40202. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  40203. * Returns the PointLight.
  40204. */
  40205. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  40206. if (this.computeTransformedInformation()) {
  40207. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  40208. return this;
  40209. }
  40210. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  40211. return this;
  40212. };
  40213. __decorate([
  40214. BABYLON.serialize()
  40215. ], PointLight.prototype, "shadowAngle", null);
  40216. return PointLight;
  40217. }(BABYLON.ShadowLight));
  40218. BABYLON.PointLight = PointLight;
  40219. })(BABYLON || (BABYLON = {}));
  40220. //# sourceMappingURL=babylon.pointLight.js.map
  40221. var BABYLON;
  40222. (function (BABYLON) {
  40223. var DirectionalLight = /** @class */ (function (_super) {
  40224. __extends(DirectionalLight, _super);
  40225. /**
  40226. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  40227. * The directional light is emitted from everywhere in the given direction.
  40228. * It can cast shawdows.
  40229. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40230. */
  40231. function DirectionalLight(name, direction, scene) {
  40232. var _this = _super.call(this, name, scene) || this;
  40233. _this._shadowFrustumSize = 0;
  40234. _this._shadowOrthoScale = 0.5;
  40235. _this.autoUpdateExtends = true;
  40236. // Cache
  40237. _this._orthoLeft = Number.MAX_VALUE;
  40238. _this._orthoRight = Number.MIN_VALUE;
  40239. _this._orthoTop = Number.MIN_VALUE;
  40240. _this._orthoBottom = Number.MAX_VALUE;
  40241. _this.position = direction.scale(-1.0);
  40242. _this.direction = direction;
  40243. return _this;
  40244. }
  40245. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  40246. /**
  40247. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  40248. */
  40249. get: function () {
  40250. return this._shadowFrustumSize;
  40251. },
  40252. /**
  40253. * Specifies a fix frustum size for the shadow generation.
  40254. */
  40255. set: function (value) {
  40256. this._shadowFrustumSize = value;
  40257. this.forceProjectionMatrixCompute();
  40258. },
  40259. enumerable: true,
  40260. configurable: true
  40261. });
  40262. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  40263. get: function () {
  40264. return this._shadowOrthoScale;
  40265. },
  40266. set: function (value) {
  40267. this._shadowOrthoScale = value;
  40268. this.forceProjectionMatrixCompute();
  40269. },
  40270. enumerable: true,
  40271. configurable: true
  40272. });
  40273. /**
  40274. * Returns the string "DirectionalLight".
  40275. */
  40276. DirectionalLight.prototype.getClassName = function () {
  40277. return "DirectionalLight";
  40278. };
  40279. /**
  40280. * Returns the integer 1.
  40281. */
  40282. DirectionalLight.prototype.getTypeID = function () {
  40283. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  40284. };
  40285. /**
  40286. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  40287. * Returns the DirectionalLight Shadow projection matrix.
  40288. */
  40289. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40290. if (this.shadowFrustumSize > 0) {
  40291. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  40292. }
  40293. else {
  40294. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  40295. }
  40296. };
  40297. /**
  40298. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  40299. * Returns the DirectionalLight Shadow projection matrix.
  40300. */
  40301. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  40302. var activeCamera = this.getScene().activeCamera;
  40303. if (!activeCamera) {
  40304. return;
  40305. }
  40306. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  40307. };
  40308. /**
  40309. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  40310. * Returns the DirectionalLight Shadow projection matrix.
  40311. */
  40312. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40313. var activeCamera = this.getScene().activeCamera;
  40314. if (!activeCamera) {
  40315. return;
  40316. }
  40317. // Check extends
  40318. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  40319. var tempVector3 = BABYLON.Vector3.Zero();
  40320. this._orthoLeft = Number.MAX_VALUE;
  40321. this._orthoRight = Number.MIN_VALUE;
  40322. this._orthoTop = Number.MIN_VALUE;
  40323. this._orthoBottom = Number.MAX_VALUE;
  40324. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  40325. var mesh = renderList[meshIndex];
  40326. if (!mesh) {
  40327. continue;
  40328. }
  40329. var boundingInfo = mesh.getBoundingInfo();
  40330. var boundingBox = boundingInfo.boundingBox;
  40331. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  40332. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  40333. if (tempVector3.x < this._orthoLeft)
  40334. this._orthoLeft = tempVector3.x;
  40335. if (tempVector3.y < this._orthoBottom)
  40336. this._orthoBottom = tempVector3.y;
  40337. if (tempVector3.x > this._orthoRight)
  40338. this._orthoRight = tempVector3.x;
  40339. if (tempVector3.y > this._orthoTop)
  40340. this._orthoTop = tempVector3.y;
  40341. }
  40342. }
  40343. }
  40344. var xOffset = this._orthoRight - this._orthoLeft;
  40345. var yOffset = this._orthoTop - this._orthoBottom;
  40346. 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);
  40347. };
  40348. DirectionalLight.prototype._buildUniformLayout = function () {
  40349. this._uniformBuffer.addUniform("vLightData", 4);
  40350. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40351. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40352. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40353. this._uniformBuffer.addUniform("depthValues", 2);
  40354. this._uniformBuffer.create();
  40355. };
  40356. /**
  40357. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  40358. * Returns the DirectionalLight.
  40359. */
  40360. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  40361. if (this.computeTransformedInformation()) {
  40362. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  40363. return this;
  40364. }
  40365. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  40366. return this;
  40367. };
  40368. /**
  40369. * Gets the minZ used for shadow according to both the scene and the light.
  40370. *
  40371. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  40372. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  40373. * @param activeCamera
  40374. */
  40375. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  40376. return 1;
  40377. };
  40378. /**
  40379. * Gets the maxZ used for shadow according to both the scene and the light.
  40380. *
  40381. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  40382. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  40383. * @param activeCamera
  40384. */
  40385. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  40386. return 1;
  40387. };
  40388. __decorate([
  40389. BABYLON.serialize()
  40390. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  40391. __decorate([
  40392. BABYLON.serialize()
  40393. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  40394. __decorate([
  40395. BABYLON.serialize()
  40396. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  40397. return DirectionalLight;
  40398. }(BABYLON.ShadowLight));
  40399. BABYLON.DirectionalLight = DirectionalLight;
  40400. })(BABYLON || (BABYLON = {}));
  40401. //# sourceMappingURL=babylon.directionalLight.js.map
  40402. var BABYLON;
  40403. (function (BABYLON) {
  40404. var SpotLight = /** @class */ (function (_super) {
  40405. __extends(SpotLight, _super);
  40406. /**
  40407. * Creates a SpotLight object in the scene with the passed parameters :
  40408. * - `position` (Vector3) is the initial SpotLight position,
  40409. * - `direction` (Vector3) is the initial SpotLight direction,
  40410. * - `angle` (float, in radians) is the spot light cone angle,
  40411. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  40412. * A spot light is a simply light oriented cone.
  40413. * It can cast shadows.
  40414. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40415. */
  40416. function SpotLight(name, position, direction, angle, exponent, scene) {
  40417. var _this = _super.call(this, name, scene) || this;
  40418. _this.position = position;
  40419. _this.direction = direction;
  40420. _this.angle = angle;
  40421. _this.exponent = exponent;
  40422. return _this;
  40423. }
  40424. Object.defineProperty(SpotLight.prototype, "angle", {
  40425. get: function () {
  40426. return this._angle;
  40427. },
  40428. set: function (value) {
  40429. this._angle = value;
  40430. this.forceProjectionMatrixCompute();
  40431. },
  40432. enumerable: true,
  40433. configurable: true
  40434. });
  40435. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  40436. get: function () {
  40437. return this._shadowAngleScale;
  40438. },
  40439. /**
  40440. * Allows scaling the angle of the light for shadow generation only.
  40441. */
  40442. set: function (value) {
  40443. this._shadowAngleScale = value;
  40444. this.forceProjectionMatrixCompute();
  40445. },
  40446. enumerable: true,
  40447. configurable: true
  40448. });
  40449. /**
  40450. * Returns the string "SpotLight".
  40451. */
  40452. SpotLight.prototype.getClassName = function () {
  40453. return "SpotLight";
  40454. };
  40455. /**
  40456. * Returns the integer 2.
  40457. */
  40458. SpotLight.prototype.getTypeID = function () {
  40459. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  40460. };
  40461. /**
  40462. * 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.
  40463. * Returns the SpotLight.
  40464. */
  40465. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40466. var activeCamera = this.getScene().activeCamera;
  40467. if (!activeCamera) {
  40468. return;
  40469. }
  40470. this._shadowAngleScale = this._shadowAngleScale || 1;
  40471. var angle = this._shadowAngleScale * this._angle;
  40472. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  40473. };
  40474. SpotLight.prototype._buildUniformLayout = function () {
  40475. this._uniformBuffer.addUniform("vLightData", 4);
  40476. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40477. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40478. this._uniformBuffer.addUniform("vLightDirection", 3);
  40479. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40480. this._uniformBuffer.addUniform("depthValues", 2);
  40481. this._uniformBuffer.create();
  40482. };
  40483. /**
  40484. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  40485. * Return the SpotLight.
  40486. */
  40487. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  40488. var normalizeDirection;
  40489. if (this.computeTransformedInformation()) {
  40490. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  40491. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  40492. }
  40493. else {
  40494. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  40495. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  40496. }
  40497. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  40498. return this;
  40499. };
  40500. __decorate([
  40501. BABYLON.serialize()
  40502. ], SpotLight.prototype, "angle", null);
  40503. __decorate([
  40504. BABYLON.serialize()
  40505. /**
  40506. * Allows scaling the angle of the light for shadow generation only.
  40507. */
  40508. ], SpotLight.prototype, "shadowAngleScale", null);
  40509. __decorate([
  40510. BABYLON.serialize()
  40511. ], SpotLight.prototype, "exponent", void 0);
  40512. return SpotLight;
  40513. }(BABYLON.ShadowLight));
  40514. BABYLON.SpotLight = SpotLight;
  40515. })(BABYLON || (BABYLON = {}));
  40516. //# sourceMappingURL=babylon.spotLight.js.map
  40517. var BABYLON;
  40518. (function (BABYLON) {
  40519. var AnimationRange = /** @class */ (function () {
  40520. function AnimationRange(name, from, to) {
  40521. this.name = name;
  40522. this.from = from;
  40523. this.to = to;
  40524. }
  40525. AnimationRange.prototype.clone = function () {
  40526. return new AnimationRange(this.name, this.from, this.to);
  40527. };
  40528. return AnimationRange;
  40529. }());
  40530. BABYLON.AnimationRange = AnimationRange;
  40531. /**
  40532. * Composed of a frame, and an action function
  40533. */
  40534. var AnimationEvent = /** @class */ (function () {
  40535. function AnimationEvent(frame, action, onlyOnce) {
  40536. this.frame = frame;
  40537. this.action = action;
  40538. this.onlyOnce = onlyOnce;
  40539. this.isDone = false;
  40540. }
  40541. return AnimationEvent;
  40542. }());
  40543. BABYLON.AnimationEvent = AnimationEvent;
  40544. var PathCursor = /** @class */ (function () {
  40545. function PathCursor(path) {
  40546. this.path = path;
  40547. this._onchange = new Array();
  40548. this.value = 0;
  40549. this.animations = new Array();
  40550. }
  40551. PathCursor.prototype.getPoint = function () {
  40552. var point = this.path.getPointAtLengthPosition(this.value);
  40553. return new BABYLON.Vector3(point.x, 0, point.y);
  40554. };
  40555. PathCursor.prototype.moveAhead = function (step) {
  40556. if (step === void 0) { step = 0.002; }
  40557. this.move(step);
  40558. return this;
  40559. };
  40560. PathCursor.prototype.moveBack = function (step) {
  40561. if (step === void 0) { step = 0.002; }
  40562. this.move(-step);
  40563. return this;
  40564. };
  40565. PathCursor.prototype.move = function (step) {
  40566. if (Math.abs(step) > 1) {
  40567. throw "step size should be less than 1.";
  40568. }
  40569. this.value += step;
  40570. this.ensureLimits();
  40571. this.raiseOnChange();
  40572. return this;
  40573. };
  40574. PathCursor.prototype.ensureLimits = function () {
  40575. while (this.value > 1) {
  40576. this.value -= 1;
  40577. }
  40578. while (this.value < 0) {
  40579. this.value += 1;
  40580. }
  40581. return this;
  40582. };
  40583. // used by animation engine
  40584. PathCursor.prototype.raiseOnChange = function () {
  40585. var _this = this;
  40586. this._onchange.forEach(function (f) { return f(_this); });
  40587. return this;
  40588. };
  40589. PathCursor.prototype.onchange = function (f) {
  40590. this._onchange.push(f);
  40591. return this;
  40592. };
  40593. return PathCursor;
  40594. }());
  40595. BABYLON.PathCursor = PathCursor;
  40596. var Animation = /** @class */ (function () {
  40597. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  40598. this.name = name;
  40599. this.targetProperty = targetProperty;
  40600. this.framePerSecond = framePerSecond;
  40601. this.dataType = dataType;
  40602. this.loopMode = loopMode;
  40603. this.enableBlending = enableBlending;
  40604. this._runtimeAnimations = new Array();
  40605. // The set of event that will be linked to this animation
  40606. this._events = new Array();
  40607. this.blendingSpeed = 0.01;
  40608. this._ranges = {};
  40609. this.targetPropertyPath = targetProperty.split(".");
  40610. this.dataType = dataType;
  40611. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  40612. }
  40613. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  40614. var dataType = undefined;
  40615. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  40616. dataType = Animation.ANIMATIONTYPE_FLOAT;
  40617. }
  40618. else if (from instanceof BABYLON.Quaternion) {
  40619. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  40620. }
  40621. else if (from instanceof BABYLON.Vector3) {
  40622. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  40623. }
  40624. else if (from instanceof BABYLON.Vector2) {
  40625. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  40626. }
  40627. else if (from instanceof BABYLON.Color3) {
  40628. dataType = Animation.ANIMATIONTYPE_COLOR3;
  40629. }
  40630. else if (from instanceof BABYLON.Size) {
  40631. dataType = Animation.ANIMATIONTYPE_SIZE;
  40632. }
  40633. if (dataType == undefined) {
  40634. return null;
  40635. }
  40636. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  40637. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  40638. animation.setKeys(keys);
  40639. if (easingFunction !== undefined) {
  40640. animation.setEasingFunction(easingFunction);
  40641. }
  40642. return animation;
  40643. };
  40644. /**
  40645. * Sets up an animation.
  40646. * @param property the property to animate
  40647. * @param animationType the animation type to apply
  40648. * @param easingFunction the easing function used in the animation
  40649. * @returns The created animation
  40650. */
  40651. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  40652. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  40653. animation.setEasingFunction(easingFunction);
  40654. return animation;
  40655. };
  40656. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  40657. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  40658. if (!animation) {
  40659. return null;
  40660. }
  40661. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  40662. };
  40663. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  40664. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  40665. if (!animation) {
  40666. return null;
  40667. }
  40668. node.animations.push(animation);
  40669. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  40670. };
  40671. /**
  40672. * Transition property of the Camera to the target Value.
  40673. * @param property The property to transition
  40674. * @param targetValue The target Value of the property
  40675. * @param host The object where the property to animate belongs
  40676. * @param scene Scene used to run the animation
  40677. * @param frameRate Framerate (in frame/s) to use
  40678. * @param transition The transition type we want to use
  40679. * @param duration The duration of the animation, in milliseconds
  40680. * @param onAnimationEnd Call back trigger at the end of the animation.
  40681. */
  40682. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  40683. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  40684. if (duration <= 0) {
  40685. host[property] = targetValue;
  40686. if (onAnimationEnd) {
  40687. onAnimationEnd();
  40688. }
  40689. return null;
  40690. }
  40691. var endFrame = frameRate * (duration / 1000);
  40692. transition.setKeys([{
  40693. frame: 0,
  40694. value: host[property].clone ? host[property].clone() : host[property]
  40695. },
  40696. {
  40697. frame: endFrame,
  40698. value: targetValue
  40699. }]);
  40700. if (!host.animations) {
  40701. host.animations = [];
  40702. }
  40703. host.animations.push(transition);
  40704. var animation = scene.beginAnimation(host, 0, endFrame, false);
  40705. animation.onAnimationEnd = onAnimationEnd;
  40706. return animation;
  40707. };
  40708. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  40709. /**
  40710. * Return the array of runtime animations currently using this animation
  40711. */
  40712. get: function () {
  40713. return this._runtimeAnimations;
  40714. },
  40715. enumerable: true,
  40716. configurable: true
  40717. });
  40718. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  40719. get: function () {
  40720. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  40721. var runtimeAnimation = _a[_i];
  40722. if (!runtimeAnimation.isStopped) {
  40723. return true;
  40724. }
  40725. }
  40726. return false;
  40727. },
  40728. enumerable: true,
  40729. configurable: true
  40730. });
  40731. // Methods
  40732. /**
  40733. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  40734. */
  40735. Animation.prototype.toString = function (fullDetails) {
  40736. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  40737. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  40738. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  40739. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  40740. if (fullDetails) {
  40741. ret += ", Ranges: {";
  40742. var first = true;
  40743. for (var name in this._ranges) {
  40744. if (first) {
  40745. ret += ", ";
  40746. first = false;
  40747. }
  40748. ret += name;
  40749. }
  40750. ret += "}";
  40751. }
  40752. return ret;
  40753. };
  40754. /**
  40755. * Add an event to this animation.
  40756. */
  40757. Animation.prototype.addEvent = function (event) {
  40758. this._events.push(event);
  40759. };
  40760. /**
  40761. * Remove all events found at the given frame
  40762. * @param frame
  40763. */
  40764. Animation.prototype.removeEvents = function (frame) {
  40765. for (var index = 0; index < this._events.length; index++) {
  40766. if (this._events[index].frame === frame) {
  40767. this._events.splice(index, 1);
  40768. index--;
  40769. }
  40770. }
  40771. };
  40772. Animation.prototype.getEvents = function () {
  40773. return this._events;
  40774. };
  40775. Animation.prototype.createRange = function (name, from, to) {
  40776. // check name not already in use; could happen for bones after serialized
  40777. if (!this._ranges[name]) {
  40778. this._ranges[name] = new AnimationRange(name, from, to);
  40779. }
  40780. };
  40781. Animation.prototype.deleteRange = function (name, deleteFrames) {
  40782. if (deleteFrames === void 0) { deleteFrames = true; }
  40783. var range = this._ranges[name];
  40784. if (!range) {
  40785. return;
  40786. }
  40787. if (deleteFrames) {
  40788. var from = range.from;
  40789. var to = range.to;
  40790. // this loop MUST go high to low for multiple splices to work
  40791. for (var key = this._keys.length - 1; key >= 0; key--) {
  40792. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  40793. this._keys.splice(key, 1);
  40794. }
  40795. }
  40796. }
  40797. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  40798. };
  40799. Animation.prototype.getRange = function (name) {
  40800. return this._ranges[name];
  40801. };
  40802. Animation.prototype.getKeys = function () {
  40803. return this._keys;
  40804. };
  40805. Animation.prototype.getHighestFrame = function () {
  40806. var ret = 0;
  40807. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  40808. if (ret < this._keys[key].frame) {
  40809. ret = this._keys[key].frame;
  40810. }
  40811. }
  40812. return ret;
  40813. };
  40814. Animation.prototype.getEasingFunction = function () {
  40815. return this._easingFunction;
  40816. };
  40817. Animation.prototype.setEasingFunction = function (easingFunction) {
  40818. this._easingFunction = easingFunction;
  40819. };
  40820. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  40821. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  40822. };
  40823. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40824. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40825. };
  40826. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  40827. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  40828. };
  40829. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40830. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  40831. };
  40832. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  40833. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  40834. };
  40835. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40836. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40837. };
  40838. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  40839. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  40840. };
  40841. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40842. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40843. };
  40844. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  40845. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  40846. };
  40847. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  40848. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  40849. };
  40850. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  40851. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  40852. };
  40853. Animation.prototype.clone = function () {
  40854. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  40855. clone.enableBlending = this.enableBlending;
  40856. clone.blendingSpeed = this.blendingSpeed;
  40857. if (this._keys) {
  40858. clone.setKeys(this._keys);
  40859. }
  40860. if (this._ranges) {
  40861. clone._ranges = {};
  40862. for (var name in this._ranges) {
  40863. var range = this._ranges[name];
  40864. if (!range) {
  40865. continue;
  40866. }
  40867. clone._ranges[name] = range.clone();
  40868. }
  40869. }
  40870. return clone;
  40871. };
  40872. Animation.prototype.setKeys = function (values) {
  40873. this._keys = values.slice(0);
  40874. };
  40875. Animation.prototype.serialize = function () {
  40876. var serializationObject = {};
  40877. serializationObject.name = this.name;
  40878. serializationObject.property = this.targetProperty;
  40879. serializationObject.framePerSecond = this.framePerSecond;
  40880. serializationObject.dataType = this.dataType;
  40881. serializationObject.loopBehavior = this.loopMode;
  40882. serializationObject.enableBlending = this.enableBlending;
  40883. serializationObject.blendingSpeed = this.blendingSpeed;
  40884. var dataType = this.dataType;
  40885. serializationObject.keys = [];
  40886. var keys = this.getKeys();
  40887. for (var index = 0; index < keys.length; index++) {
  40888. var animationKey = keys[index];
  40889. var key = {};
  40890. key.frame = animationKey.frame;
  40891. switch (dataType) {
  40892. case Animation.ANIMATIONTYPE_FLOAT:
  40893. key.values = [animationKey.value];
  40894. break;
  40895. case Animation.ANIMATIONTYPE_QUATERNION:
  40896. case Animation.ANIMATIONTYPE_MATRIX:
  40897. case Animation.ANIMATIONTYPE_VECTOR3:
  40898. case Animation.ANIMATIONTYPE_COLOR3:
  40899. key.values = animationKey.value.asArray();
  40900. break;
  40901. }
  40902. serializationObject.keys.push(key);
  40903. }
  40904. serializationObject.ranges = [];
  40905. for (var name in this._ranges) {
  40906. var source = this._ranges[name];
  40907. if (!source) {
  40908. continue;
  40909. }
  40910. var range = {};
  40911. range.name = name;
  40912. range.from = source.from;
  40913. range.to = source.to;
  40914. serializationObject.ranges.push(range);
  40915. }
  40916. return serializationObject;
  40917. };
  40918. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  40919. get: function () {
  40920. return Animation._ANIMATIONTYPE_FLOAT;
  40921. },
  40922. enumerable: true,
  40923. configurable: true
  40924. });
  40925. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  40926. get: function () {
  40927. return Animation._ANIMATIONTYPE_VECTOR3;
  40928. },
  40929. enumerable: true,
  40930. configurable: true
  40931. });
  40932. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  40933. get: function () {
  40934. return Animation._ANIMATIONTYPE_VECTOR2;
  40935. },
  40936. enumerable: true,
  40937. configurable: true
  40938. });
  40939. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  40940. get: function () {
  40941. return Animation._ANIMATIONTYPE_SIZE;
  40942. },
  40943. enumerable: true,
  40944. configurable: true
  40945. });
  40946. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  40947. get: function () {
  40948. return Animation._ANIMATIONTYPE_QUATERNION;
  40949. },
  40950. enumerable: true,
  40951. configurable: true
  40952. });
  40953. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  40954. get: function () {
  40955. return Animation._ANIMATIONTYPE_MATRIX;
  40956. },
  40957. enumerable: true,
  40958. configurable: true
  40959. });
  40960. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  40961. get: function () {
  40962. return Animation._ANIMATIONTYPE_COLOR3;
  40963. },
  40964. enumerable: true,
  40965. configurable: true
  40966. });
  40967. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  40968. get: function () {
  40969. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  40970. },
  40971. enumerable: true,
  40972. configurable: true
  40973. });
  40974. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  40975. get: function () {
  40976. return Animation._ANIMATIONLOOPMODE_CYCLE;
  40977. },
  40978. enumerable: true,
  40979. configurable: true
  40980. });
  40981. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  40982. get: function () {
  40983. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  40984. },
  40985. enumerable: true,
  40986. configurable: true
  40987. });
  40988. Animation.Parse = function (parsedAnimation) {
  40989. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  40990. var dataType = parsedAnimation.dataType;
  40991. var keys = [];
  40992. var data;
  40993. var index;
  40994. if (parsedAnimation.enableBlending) {
  40995. animation.enableBlending = parsedAnimation.enableBlending;
  40996. }
  40997. if (parsedAnimation.blendingSpeed) {
  40998. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  40999. }
  41000. for (index = 0; index < parsedAnimation.keys.length; index++) {
  41001. var key = parsedAnimation.keys[index];
  41002. var inTangent;
  41003. var outTangent;
  41004. switch (dataType) {
  41005. case Animation.ANIMATIONTYPE_FLOAT:
  41006. data = key.values[0];
  41007. if (key.values.length >= 1) {
  41008. inTangent = key.values[1];
  41009. }
  41010. if (key.values.length >= 2) {
  41011. outTangent = key.values[2];
  41012. }
  41013. break;
  41014. case Animation.ANIMATIONTYPE_QUATERNION:
  41015. data = BABYLON.Quaternion.FromArray(key.values);
  41016. if (key.values.length >= 8) {
  41017. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  41018. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  41019. inTangent = _inTangent;
  41020. }
  41021. }
  41022. if (key.values.length >= 12) {
  41023. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  41024. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  41025. outTangent = _outTangent;
  41026. }
  41027. }
  41028. break;
  41029. case Animation.ANIMATIONTYPE_MATRIX:
  41030. data = BABYLON.Matrix.FromArray(key.values);
  41031. break;
  41032. case Animation.ANIMATIONTYPE_COLOR3:
  41033. data = BABYLON.Color3.FromArray(key.values);
  41034. break;
  41035. case Animation.ANIMATIONTYPE_VECTOR3:
  41036. default:
  41037. data = BABYLON.Vector3.FromArray(key.values);
  41038. break;
  41039. }
  41040. var keyData = {};
  41041. keyData.frame = key.frame;
  41042. keyData.value = data;
  41043. if (inTangent != undefined) {
  41044. keyData.inTangent = inTangent;
  41045. }
  41046. if (outTangent != undefined) {
  41047. keyData.outTangent = outTangent;
  41048. }
  41049. keys.push(keyData);
  41050. }
  41051. animation.setKeys(keys);
  41052. if (parsedAnimation.ranges) {
  41053. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  41054. data = parsedAnimation.ranges[index];
  41055. animation.createRange(data.name, data.from, data.to);
  41056. }
  41057. }
  41058. return animation;
  41059. };
  41060. Animation.AppendSerializedAnimations = function (source, destination) {
  41061. if (source.animations) {
  41062. destination.animations = [];
  41063. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  41064. var animation = source.animations[animationIndex];
  41065. destination.animations.push(animation.serialize());
  41066. }
  41067. }
  41068. };
  41069. Animation.AllowMatricesInterpolation = false;
  41070. // Statics
  41071. Animation._ANIMATIONTYPE_FLOAT = 0;
  41072. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  41073. Animation._ANIMATIONTYPE_QUATERNION = 2;
  41074. Animation._ANIMATIONTYPE_MATRIX = 3;
  41075. Animation._ANIMATIONTYPE_COLOR3 = 4;
  41076. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  41077. Animation._ANIMATIONTYPE_SIZE = 6;
  41078. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  41079. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  41080. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  41081. return Animation;
  41082. }());
  41083. BABYLON.Animation = Animation;
  41084. })(BABYLON || (BABYLON = {}));
  41085. //# sourceMappingURL=babylon.animation.js.map
  41086. var BABYLON;
  41087. (function (BABYLON) {
  41088. var RuntimeAnimation = /** @class */ (function () {
  41089. function RuntimeAnimation(target, animation) {
  41090. this._offsetsCache = {};
  41091. this._highLimitsCache = {};
  41092. this._stopped = false;
  41093. this._blendingFactor = 0;
  41094. this._ratioOffset = 0;
  41095. this._animation = animation;
  41096. this._target = target;
  41097. animation._runtimeAnimations.push(this);
  41098. }
  41099. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  41100. get: function () {
  41101. return this._animation;
  41102. },
  41103. enumerable: true,
  41104. configurable: true
  41105. });
  41106. RuntimeAnimation.prototype.reset = function () {
  41107. this._offsetsCache = {};
  41108. this._highLimitsCache = {};
  41109. this.currentFrame = 0;
  41110. this._blendingFactor = 0;
  41111. this._originalBlendValue = null;
  41112. };
  41113. RuntimeAnimation.prototype.isStopped = function () {
  41114. return this._stopped;
  41115. };
  41116. RuntimeAnimation.prototype.dispose = function () {
  41117. var index = this._animation.runtimeAnimations.indexOf(this);
  41118. if (index > -1) {
  41119. this._animation.runtimeAnimations.splice(index, 1);
  41120. }
  41121. };
  41122. RuntimeAnimation.prototype._getKeyValue = function (value) {
  41123. if (typeof value === "function") {
  41124. return value();
  41125. }
  41126. return value;
  41127. };
  41128. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  41129. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  41130. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  41131. }
  41132. this.currentFrame = currentFrame;
  41133. var keys = this._animation.getKeys();
  41134. // Try to get a hash to find the right key
  41135. 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));
  41136. if (keys[startKeyIndex].frame >= currentFrame) {
  41137. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  41138. startKeyIndex--;
  41139. }
  41140. }
  41141. for (var key = startKeyIndex; key < keys.length; key++) {
  41142. var endKey = keys[key + 1];
  41143. if (endKey.frame >= currentFrame) {
  41144. var startKey = keys[key];
  41145. var startValue = this._getKeyValue(startKey.value);
  41146. var endValue = this._getKeyValue(endKey.value);
  41147. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  41148. var frameDelta = endKey.frame - startKey.frame;
  41149. // gradient : percent of currentFrame between the frame inf and the frame sup
  41150. var gradient = (currentFrame - startKey.frame) / frameDelta;
  41151. // check for easingFunction and correction of gradient
  41152. var easingFunction = this._animation.getEasingFunction();
  41153. if (easingFunction != null) {
  41154. gradient = easingFunction.ease(gradient);
  41155. }
  41156. switch (this._animation.dataType) {
  41157. // Float
  41158. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  41159. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  41160. switch (loopMode) {
  41161. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41162. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41163. return floatValue;
  41164. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41165. return offsetValue * repeatCount + floatValue;
  41166. }
  41167. break;
  41168. // Quaternion
  41169. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  41170. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  41171. switch (loopMode) {
  41172. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41173. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41174. return quatValue;
  41175. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41176. return quatValue.add(offsetValue.scale(repeatCount));
  41177. }
  41178. return quatValue;
  41179. // Vector3
  41180. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  41181. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  41182. switch (loopMode) {
  41183. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41184. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41185. return vec3Value;
  41186. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41187. return vec3Value.add(offsetValue.scale(repeatCount));
  41188. }
  41189. // Vector2
  41190. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  41191. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  41192. switch (loopMode) {
  41193. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41194. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41195. return vec2Value;
  41196. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41197. return vec2Value.add(offsetValue.scale(repeatCount));
  41198. }
  41199. // Size
  41200. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  41201. switch (loopMode) {
  41202. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41203. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41204. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  41205. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41206. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  41207. }
  41208. // Color3
  41209. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  41210. switch (loopMode) {
  41211. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41212. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41213. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  41214. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41215. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  41216. }
  41217. // Matrix
  41218. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  41219. switch (loopMode) {
  41220. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41221. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41222. if (BABYLON.Animation.AllowMatricesInterpolation) {
  41223. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  41224. }
  41225. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41226. return startValue;
  41227. }
  41228. default:
  41229. break;
  41230. }
  41231. break;
  41232. }
  41233. }
  41234. return this._getKeyValue(keys[keys.length - 1].value);
  41235. };
  41236. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  41237. if (blend === void 0) { blend = false; }
  41238. // Set value
  41239. var path;
  41240. var destination;
  41241. var targetPropertyPath = this._animation.targetPropertyPath;
  41242. if (targetPropertyPath.length > 1) {
  41243. var property = this._target[targetPropertyPath[0]];
  41244. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  41245. property = property[targetPropertyPath[index]];
  41246. }
  41247. path = targetPropertyPath[targetPropertyPath.length - 1];
  41248. destination = property;
  41249. }
  41250. else {
  41251. path = targetPropertyPath[0];
  41252. destination = this._target;
  41253. }
  41254. // Blending
  41255. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  41256. if (!this._originalBlendValue) {
  41257. if (destination[path].clone) {
  41258. this._originalBlendValue = destination[path].clone();
  41259. }
  41260. else {
  41261. this._originalBlendValue = destination[path];
  41262. }
  41263. }
  41264. if (this._originalBlendValue.prototype) {
  41265. if (this._originalBlendValue.prototype.Lerp) {
  41266. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  41267. }
  41268. else {
  41269. destination[path] = currentValue;
  41270. }
  41271. }
  41272. else if (this._originalBlendValue.m) {
  41273. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  41274. }
  41275. else {
  41276. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  41277. }
  41278. this._blendingFactor += this._animation.blendingSpeed;
  41279. }
  41280. else {
  41281. destination[path] = currentValue;
  41282. }
  41283. if (this._target.markAsDirty) {
  41284. this._target.markAsDirty(this._animation.targetProperty);
  41285. }
  41286. };
  41287. RuntimeAnimation.prototype.goToFrame = function (frame) {
  41288. var keys = this._animation.getKeys();
  41289. if (frame < keys[0].frame) {
  41290. frame = keys[0].frame;
  41291. }
  41292. else if (frame > keys[keys.length - 1].frame) {
  41293. frame = keys[keys.length - 1].frame;
  41294. }
  41295. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  41296. this.setValue(currentValue);
  41297. };
  41298. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  41299. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  41300. this._ratioOffset = this._previousRatio - newRatio;
  41301. };
  41302. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  41303. if (blend === void 0) { blend = false; }
  41304. var targetPropertyPath = this._animation.targetPropertyPath;
  41305. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  41306. this._stopped = true;
  41307. return false;
  41308. }
  41309. var returnValue = true;
  41310. var keys = this._animation.getKeys();
  41311. // Adding a start key at frame 0 if missing
  41312. if (keys[0].frame !== 0) {
  41313. var newKey = { frame: 0, value: keys[0].value };
  41314. keys.splice(0, 0, newKey);
  41315. }
  41316. // Check limits
  41317. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  41318. from = keys[0].frame;
  41319. }
  41320. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  41321. to = keys[keys.length - 1].frame;
  41322. }
  41323. //to and from cannot be the same key
  41324. if (from === to) {
  41325. if (from > keys[0].frame) {
  41326. from--;
  41327. }
  41328. else if (to < keys[keys.length - 1].frame) {
  41329. to++;
  41330. }
  41331. }
  41332. // Compute ratio
  41333. var range = to - from;
  41334. var offsetValue;
  41335. // ratio represents the frame delta between from and to
  41336. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  41337. var highLimitValue = 0;
  41338. this._previousDelay = delay;
  41339. this._previousRatio = ratio;
  41340. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  41341. returnValue = false;
  41342. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  41343. }
  41344. else {
  41345. // Get max value if required
  41346. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  41347. var keyOffset = to.toString() + from.toString();
  41348. if (!this._offsetsCache[keyOffset]) {
  41349. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  41350. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  41351. switch (this._animation.dataType) {
  41352. // Float
  41353. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  41354. this._offsetsCache[keyOffset] = toValue - fromValue;
  41355. break;
  41356. // Quaternion
  41357. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  41358. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41359. break;
  41360. // Vector3
  41361. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  41362. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41363. // Vector2
  41364. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  41365. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41366. // Size
  41367. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  41368. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41369. // Color3
  41370. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  41371. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41372. default:
  41373. break;
  41374. }
  41375. this._highLimitsCache[keyOffset] = toValue;
  41376. }
  41377. highLimitValue = this._highLimitsCache[keyOffset];
  41378. offsetValue = this._offsetsCache[keyOffset];
  41379. }
  41380. }
  41381. if (offsetValue === undefined) {
  41382. switch (this._animation.dataType) {
  41383. // Float
  41384. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  41385. offsetValue = 0;
  41386. break;
  41387. // Quaternion
  41388. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  41389. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  41390. break;
  41391. // Vector3
  41392. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  41393. offsetValue = BABYLON.Vector3.Zero();
  41394. break;
  41395. // Vector2
  41396. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  41397. offsetValue = BABYLON.Vector2.Zero();
  41398. break;
  41399. // Size
  41400. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  41401. offsetValue = BABYLON.Size.Zero();
  41402. break;
  41403. // Color3
  41404. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  41405. offsetValue = BABYLON.Color3.Black();
  41406. }
  41407. }
  41408. // Compute value
  41409. var repeatCount = (ratio / range) >> 0;
  41410. var currentFrame = returnValue ? from + ratio % range : to;
  41411. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  41412. // Set value
  41413. this.setValue(currentValue);
  41414. // Check events
  41415. var events = this._animation.getEvents();
  41416. for (var index = 0; index < events.length; index++) {
  41417. // Make sure current frame has passed event frame and that event frame is within the current range
  41418. // Also, handle both forward and reverse animations
  41419. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  41420. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  41421. var event = events[index];
  41422. if (!event.isDone) {
  41423. // If event should be done only once, remove it.
  41424. if (event.onlyOnce) {
  41425. events.splice(index, 1);
  41426. index--;
  41427. }
  41428. event.isDone = true;
  41429. event.action();
  41430. } // Don't do anything if the event has already be done.
  41431. }
  41432. else if (events[index].isDone && !events[index].onlyOnce) {
  41433. // reset event, the animation is looping
  41434. events[index].isDone = false;
  41435. }
  41436. }
  41437. if (!returnValue) {
  41438. this._stopped = true;
  41439. }
  41440. return returnValue;
  41441. };
  41442. return RuntimeAnimation;
  41443. }());
  41444. BABYLON.RuntimeAnimation = RuntimeAnimation;
  41445. })(BABYLON || (BABYLON = {}));
  41446. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  41447. var BABYLON;
  41448. (function (BABYLON) {
  41449. var Animatable = /** @class */ (function () {
  41450. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  41451. if (fromFrame === void 0) { fromFrame = 0; }
  41452. if (toFrame === void 0) { toFrame = 100; }
  41453. if (loopAnimation === void 0) { loopAnimation = false; }
  41454. if (speedRatio === void 0) { speedRatio = 1.0; }
  41455. this.target = target;
  41456. this.fromFrame = fromFrame;
  41457. this.toFrame = toFrame;
  41458. this.loopAnimation = loopAnimation;
  41459. this.onAnimationEnd = onAnimationEnd;
  41460. this._localDelayOffset = null;
  41461. this._pausedDelay = null;
  41462. this._runtimeAnimations = new Array();
  41463. this._paused = false;
  41464. this._speedRatio = 1;
  41465. this.animationStarted = false;
  41466. if (animations) {
  41467. this.appendAnimations(target, animations);
  41468. }
  41469. this._speedRatio = speedRatio;
  41470. this._scene = scene;
  41471. scene._activeAnimatables.push(this);
  41472. }
  41473. Object.defineProperty(Animatable.prototype, "speedRatio", {
  41474. get: function () {
  41475. return this._speedRatio;
  41476. },
  41477. set: function (value) {
  41478. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  41479. var animation = this._runtimeAnimations[index];
  41480. animation._prepareForSpeedRatioChange(value);
  41481. }
  41482. this._speedRatio = value;
  41483. },
  41484. enumerable: true,
  41485. configurable: true
  41486. });
  41487. // Methods
  41488. Animatable.prototype.getAnimations = function () {
  41489. return this._runtimeAnimations;
  41490. };
  41491. Animatable.prototype.appendAnimations = function (target, animations) {
  41492. for (var index = 0; index < animations.length; index++) {
  41493. var animation = animations[index];
  41494. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  41495. }
  41496. };
  41497. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  41498. var runtimeAnimations = this._runtimeAnimations;
  41499. for (var index = 0; index < runtimeAnimations.length; index++) {
  41500. if (runtimeAnimations[index].animation.targetProperty === property) {
  41501. return runtimeAnimations[index].animation;
  41502. }
  41503. }
  41504. return null;
  41505. };
  41506. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  41507. var runtimeAnimations = this._runtimeAnimations;
  41508. for (var index = 0; index < runtimeAnimations.length; index++) {
  41509. if (runtimeAnimations[index].animation.targetProperty === property) {
  41510. return runtimeAnimations[index];
  41511. }
  41512. }
  41513. return null;
  41514. };
  41515. Animatable.prototype.reset = function () {
  41516. var runtimeAnimations = this._runtimeAnimations;
  41517. for (var index = 0; index < runtimeAnimations.length; index++) {
  41518. runtimeAnimations[index].reset();
  41519. }
  41520. this._localDelayOffset = null;
  41521. this._pausedDelay = null;
  41522. };
  41523. Animatable.prototype.enableBlending = function (blendingSpeed) {
  41524. var runtimeAnimations = this._runtimeAnimations;
  41525. for (var index = 0; index < runtimeAnimations.length; index++) {
  41526. runtimeAnimations[index].animation.enableBlending = true;
  41527. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  41528. }
  41529. };
  41530. Animatable.prototype.disableBlending = function () {
  41531. var runtimeAnimations = this._runtimeAnimations;
  41532. for (var index = 0; index < runtimeAnimations.length; index++) {
  41533. runtimeAnimations[index].animation.enableBlending = false;
  41534. }
  41535. };
  41536. Animatable.prototype.goToFrame = function (frame) {
  41537. var runtimeAnimations = this._runtimeAnimations;
  41538. if (runtimeAnimations[0]) {
  41539. var fps = runtimeAnimations[0].animation.framePerSecond;
  41540. var currentFrame = runtimeAnimations[0].currentFrame;
  41541. var adjustTime = frame - currentFrame;
  41542. var delay = adjustTime * 1000 / fps;
  41543. if (this._localDelayOffset === null) {
  41544. this._localDelayOffset = 0;
  41545. }
  41546. this._localDelayOffset -= delay;
  41547. }
  41548. for (var index = 0; index < runtimeAnimations.length; index++) {
  41549. runtimeAnimations[index].goToFrame(frame);
  41550. }
  41551. };
  41552. Animatable.prototype.pause = function () {
  41553. if (this._paused) {
  41554. return;
  41555. }
  41556. this._paused = true;
  41557. };
  41558. Animatable.prototype.restart = function () {
  41559. this._paused = false;
  41560. };
  41561. Animatable.prototype.stop = function (animationName) {
  41562. if (animationName) {
  41563. var idx = this._scene._activeAnimatables.indexOf(this);
  41564. if (idx > -1) {
  41565. var runtimeAnimations = this._runtimeAnimations;
  41566. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  41567. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  41568. continue;
  41569. }
  41570. runtimeAnimations[index].dispose();
  41571. runtimeAnimations.splice(index, 1);
  41572. }
  41573. if (runtimeAnimations.length == 0) {
  41574. this._scene._activeAnimatables.splice(idx, 1);
  41575. if (this.onAnimationEnd) {
  41576. this.onAnimationEnd();
  41577. }
  41578. }
  41579. }
  41580. }
  41581. else {
  41582. var index = this._scene._activeAnimatables.indexOf(this);
  41583. if (index > -1) {
  41584. this._scene._activeAnimatables.splice(index, 1);
  41585. var runtimeAnimations = this._runtimeAnimations;
  41586. for (var index = 0; index < runtimeAnimations.length; index++) {
  41587. runtimeAnimations[index].dispose();
  41588. }
  41589. if (this.onAnimationEnd) {
  41590. this.onAnimationEnd();
  41591. }
  41592. }
  41593. }
  41594. };
  41595. Animatable.prototype._animate = function (delay) {
  41596. if (this._paused) {
  41597. this.animationStarted = false;
  41598. if (this._pausedDelay === null) {
  41599. this._pausedDelay = delay;
  41600. }
  41601. return true;
  41602. }
  41603. if (this._localDelayOffset === null) {
  41604. this._localDelayOffset = delay;
  41605. }
  41606. else if (this._pausedDelay !== null) {
  41607. this._localDelayOffset += delay - this._pausedDelay;
  41608. this._pausedDelay = null;
  41609. }
  41610. // Animating
  41611. var running = false;
  41612. var runtimeAnimations = this._runtimeAnimations;
  41613. var index;
  41614. for (index = 0; index < runtimeAnimations.length; index++) {
  41615. var animation = runtimeAnimations[index];
  41616. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  41617. running = running || isRunning;
  41618. }
  41619. this.animationStarted = running;
  41620. if (!running) {
  41621. // Remove from active animatables
  41622. index = this._scene._activeAnimatables.indexOf(this);
  41623. this._scene._activeAnimatables.splice(index, 1);
  41624. // Dispose all runtime animations
  41625. for (index = 0; index < runtimeAnimations.length; index++) {
  41626. runtimeAnimations[index].dispose();
  41627. }
  41628. }
  41629. if (!running && this.onAnimationEnd) {
  41630. this.onAnimationEnd();
  41631. this.onAnimationEnd = null;
  41632. }
  41633. return running;
  41634. };
  41635. return Animatable;
  41636. }());
  41637. BABYLON.Animatable = Animatable;
  41638. })(BABYLON || (BABYLON = {}));
  41639. //# sourceMappingURL=babylon.animatable.js.map
  41640. var BABYLON;
  41641. (function (BABYLON) {
  41642. var EasingFunction = /** @class */ (function () {
  41643. function EasingFunction() {
  41644. // Properties
  41645. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  41646. }
  41647. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  41648. get: function () {
  41649. return EasingFunction._EASINGMODE_EASEIN;
  41650. },
  41651. enumerable: true,
  41652. configurable: true
  41653. });
  41654. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  41655. get: function () {
  41656. return EasingFunction._EASINGMODE_EASEOUT;
  41657. },
  41658. enumerable: true,
  41659. configurable: true
  41660. });
  41661. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  41662. get: function () {
  41663. return EasingFunction._EASINGMODE_EASEINOUT;
  41664. },
  41665. enumerable: true,
  41666. configurable: true
  41667. });
  41668. EasingFunction.prototype.setEasingMode = function (easingMode) {
  41669. var n = Math.min(Math.max(easingMode, 0), 2);
  41670. this._easingMode = n;
  41671. };
  41672. EasingFunction.prototype.getEasingMode = function () {
  41673. return this._easingMode;
  41674. };
  41675. EasingFunction.prototype.easeInCore = function (gradient) {
  41676. throw new Error('You must implement this method');
  41677. };
  41678. EasingFunction.prototype.ease = function (gradient) {
  41679. switch (this._easingMode) {
  41680. case EasingFunction.EASINGMODE_EASEIN:
  41681. return this.easeInCore(gradient);
  41682. case EasingFunction.EASINGMODE_EASEOUT:
  41683. return (1 - this.easeInCore(1 - gradient));
  41684. }
  41685. if (gradient >= 0.5) {
  41686. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  41687. }
  41688. return (this.easeInCore(gradient * 2) * 0.5);
  41689. };
  41690. //Statics
  41691. EasingFunction._EASINGMODE_EASEIN = 0;
  41692. EasingFunction._EASINGMODE_EASEOUT = 1;
  41693. EasingFunction._EASINGMODE_EASEINOUT = 2;
  41694. return EasingFunction;
  41695. }());
  41696. BABYLON.EasingFunction = EasingFunction;
  41697. var CircleEase = /** @class */ (function (_super) {
  41698. __extends(CircleEase, _super);
  41699. function CircleEase() {
  41700. return _super !== null && _super.apply(this, arguments) || this;
  41701. }
  41702. CircleEase.prototype.easeInCore = function (gradient) {
  41703. gradient = Math.max(0, Math.min(1, gradient));
  41704. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  41705. };
  41706. return CircleEase;
  41707. }(EasingFunction));
  41708. BABYLON.CircleEase = CircleEase;
  41709. var BackEase = /** @class */ (function (_super) {
  41710. __extends(BackEase, _super);
  41711. function BackEase(amplitude) {
  41712. if (amplitude === void 0) { amplitude = 1; }
  41713. var _this = _super.call(this) || this;
  41714. _this.amplitude = amplitude;
  41715. return _this;
  41716. }
  41717. BackEase.prototype.easeInCore = function (gradient) {
  41718. var num = Math.max(0, this.amplitude);
  41719. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  41720. };
  41721. return BackEase;
  41722. }(EasingFunction));
  41723. BABYLON.BackEase = BackEase;
  41724. var BounceEase = /** @class */ (function (_super) {
  41725. __extends(BounceEase, _super);
  41726. function BounceEase(bounces, bounciness) {
  41727. if (bounces === void 0) { bounces = 3; }
  41728. if (bounciness === void 0) { bounciness = 2; }
  41729. var _this = _super.call(this) || this;
  41730. _this.bounces = bounces;
  41731. _this.bounciness = bounciness;
  41732. return _this;
  41733. }
  41734. BounceEase.prototype.easeInCore = function (gradient) {
  41735. var y = Math.max(0.0, this.bounces);
  41736. var bounciness = this.bounciness;
  41737. if (bounciness <= 1.0) {
  41738. bounciness = 1.001;
  41739. }
  41740. var num9 = Math.pow(bounciness, y);
  41741. var num5 = 1.0 - bounciness;
  41742. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  41743. var num15 = gradient * num4;
  41744. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  41745. var num3 = Math.floor(num65);
  41746. var num13 = num3 + 1.0;
  41747. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  41748. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  41749. var num7 = (num8 + num12) * 0.5;
  41750. var num6 = gradient - num7;
  41751. var num2 = num7 - num8;
  41752. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  41753. };
  41754. return BounceEase;
  41755. }(EasingFunction));
  41756. BABYLON.BounceEase = BounceEase;
  41757. var CubicEase = /** @class */ (function (_super) {
  41758. __extends(CubicEase, _super);
  41759. function CubicEase() {
  41760. return _super !== null && _super.apply(this, arguments) || this;
  41761. }
  41762. CubicEase.prototype.easeInCore = function (gradient) {
  41763. return (gradient * gradient * gradient);
  41764. };
  41765. return CubicEase;
  41766. }(EasingFunction));
  41767. BABYLON.CubicEase = CubicEase;
  41768. var ElasticEase = /** @class */ (function (_super) {
  41769. __extends(ElasticEase, _super);
  41770. function ElasticEase(oscillations, springiness) {
  41771. if (oscillations === void 0) { oscillations = 3; }
  41772. if (springiness === void 0) { springiness = 3; }
  41773. var _this = _super.call(this) || this;
  41774. _this.oscillations = oscillations;
  41775. _this.springiness = springiness;
  41776. return _this;
  41777. }
  41778. ElasticEase.prototype.easeInCore = function (gradient) {
  41779. var num2;
  41780. var num3 = Math.max(0.0, this.oscillations);
  41781. var num = Math.max(0.0, this.springiness);
  41782. if (num == 0) {
  41783. num2 = gradient;
  41784. }
  41785. else {
  41786. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  41787. }
  41788. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  41789. };
  41790. return ElasticEase;
  41791. }(EasingFunction));
  41792. BABYLON.ElasticEase = ElasticEase;
  41793. var ExponentialEase = /** @class */ (function (_super) {
  41794. __extends(ExponentialEase, _super);
  41795. function ExponentialEase(exponent) {
  41796. if (exponent === void 0) { exponent = 2; }
  41797. var _this = _super.call(this) || this;
  41798. _this.exponent = exponent;
  41799. return _this;
  41800. }
  41801. ExponentialEase.prototype.easeInCore = function (gradient) {
  41802. if (this.exponent <= 0) {
  41803. return gradient;
  41804. }
  41805. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  41806. };
  41807. return ExponentialEase;
  41808. }(EasingFunction));
  41809. BABYLON.ExponentialEase = ExponentialEase;
  41810. var PowerEase = /** @class */ (function (_super) {
  41811. __extends(PowerEase, _super);
  41812. function PowerEase(power) {
  41813. if (power === void 0) { power = 2; }
  41814. var _this = _super.call(this) || this;
  41815. _this.power = power;
  41816. return _this;
  41817. }
  41818. PowerEase.prototype.easeInCore = function (gradient) {
  41819. var y = Math.max(0.0, this.power);
  41820. return Math.pow(gradient, y);
  41821. };
  41822. return PowerEase;
  41823. }(EasingFunction));
  41824. BABYLON.PowerEase = PowerEase;
  41825. var QuadraticEase = /** @class */ (function (_super) {
  41826. __extends(QuadraticEase, _super);
  41827. function QuadraticEase() {
  41828. return _super !== null && _super.apply(this, arguments) || this;
  41829. }
  41830. QuadraticEase.prototype.easeInCore = function (gradient) {
  41831. return (gradient * gradient);
  41832. };
  41833. return QuadraticEase;
  41834. }(EasingFunction));
  41835. BABYLON.QuadraticEase = QuadraticEase;
  41836. var QuarticEase = /** @class */ (function (_super) {
  41837. __extends(QuarticEase, _super);
  41838. function QuarticEase() {
  41839. return _super !== null && _super.apply(this, arguments) || this;
  41840. }
  41841. QuarticEase.prototype.easeInCore = function (gradient) {
  41842. return (gradient * gradient * gradient * gradient);
  41843. };
  41844. return QuarticEase;
  41845. }(EasingFunction));
  41846. BABYLON.QuarticEase = QuarticEase;
  41847. var QuinticEase = /** @class */ (function (_super) {
  41848. __extends(QuinticEase, _super);
  41849. function QuinticEase() {
  41850. return _super !== null && _super.apply(this, arguments) || this;
  41851. }
  41852. QuinticEase.prototype.easeInCore = function (gradient) {
  41853. return (gradient * gradient * gradient * gradient * gradient);
  41854. };
  41855. return QuinticEase;
  41856. }(EasingFunction));
  41857. BABYLON.QuinticEase = QuinticEase;
  41858. var SineEase = /** @class */ (function (_super) {
  41859. __extends(SineEase, _super);
  41860. function SineEase() {
  41861. return _super !== null && _super.apply(this, arguments) || this;
  41862. }
  41863. SineEase.prototype.easeInCore = function (gradient) {
  41864. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  41865. };
  41866. return SineEase;
  41867. }(EasingFunction));
  41868. BABYLON.SineEase = SineEase;
  41869. var BezierCurveEase = /** @class */ (function (_super) {
  41870. __extends(BezierCurveEase, _super);
  41871. function BezierCurveEase(x1, y1, x2, y2) {
  41872. if (x1 === void 0) { x1 = 0; }
  41873. if (y1 === void 0) { y1 = 0; }
  41874. if (x2 === void 0) { x2 = 1; }
  41875. if (y2 === void 0) { y2 = 1; }
  41876. var _this = _super.call(this) || this;
  41877. _this.x1 = x1;
  41878. _this.y1 = y1;
  41879. _this.x2 = x2;
  41880. _this.y2 = y2;
  41881. return _this;
  41882. }
  41883. BezierCurveEase.prototype.easeInCore = function (gradient) {
  41884. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  41885. };
  41886. return BezierCurveEase;
  41887. }(EasingFunction));
  41888. BABYLON.BezierCurveEase = BezierCurveEase;
  41889. })(BABYLON || (BABYLON = {}));
  41890. //# sourceMappingURL=babylon.easing.js.map
  41891. var BABYLON;
  41892. (function (BABYLON) {
  41893. var Condition = /** @class */ (function () {
  41894. function Condition(actionManager) {
  41895. this._actionManager = actionManager;
  41896. }
  41897. Condition.prototype.isValid = function () {
  41898. return true;
  41899. };
  41900. Condition.prototype._getProperty = function (propertyPath) {
  41901. return this._actionManager._getProperty(propertyPath);
  41902. };
  41903. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  41904. return this._actionManager._getEffectiveTarget(target, propertyPath);
  41905. };
  41906. Condition.prototype.serialize = function () {
  41907. };
  41908. Condition.prototype._serialize = function (serializedCondition) {
  41909. return {
  41910. type: 2,
  41911. children: [],
  41912. name: serializedCondition.name,
  41913. properties: serializedCondition.properties
  41914. };
  41915. };
  41916. return Condition;
  41917. }());
  41918. BABYLON.Condition = Condition;
  41919. var ValueCondition = /** @class */ (function (_super) {
  41920. __extends(ValueCondition, _super);
  41921. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  41922. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  41923. var _this = _super.call(this, actionManager) || this;
  41924. _this.propertyPath = propertyPath;
  41925. _this.value = value;
  41926. _this.operator = operator;
  41927. _this._target = target;
  41928. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  41929. _this._property = _this._getProperty(_this.propertyPath);
  41930. return _this;
  41931. }
  41932. Object.defineProperty(ValueCondition, "IsEqual", {
  41933. get: function () {
  41934. return ValueCondition._IsEqual;
  41935. },
  41936. enumerable: true,
  41937. configurable: true
  41938. });
  41939. Object.defineProperty(ValueCondition, "IsDifferent", {
  41940. get: function () {
  41941. return ValueCondition._IsDifferent;
  41942. },
  41943. enumerable: true,
  41944. configurable: true
  41945. });
  41946. Object.defineProperty(ValueCondition, "IsGreater", {
  41947. get: function () {
  41948. return ValueCondition._IsGreater;
  41949. },
  41950. enumerable: true,
  41951. configurable: true
  41952. });
  41953. Object.defineProperty(ValueCondition, "IsLesser", {
  41954. get: function () {
  41955. return ValueCondition._IsLesser;
  41956. },
  41957. enumerable: true,
  41958. configurable: true
  41959. });
  41960. // Methods
  41961. ValueCondition.prototype.isValid = function () {
  41962. switch (this.operator) {
  41963. case ValueCondition.IsGreater:
  41964. return this._effectiveTarget[this._property] > this.value;
  41965. case ValueCondition.IsLesser:
  41966. return this._effectiveTarget[this._property] < this.value;
  41967. case ValueCondition.IsEqual:
  41968. case ValueCondition.IsDifferent:
  41969. var check;
  41970. if (this.value.equals) {
  41971. check = this.value.equals(this._effectiveTarget[this._property]);
  41972. }
  41973. else {
  41974. check = this.value === this._effectiveTarget[this._property];
  41975. }
  41976. return this.operator === ValueCondition.IsEqual ? check : !check;
  41977. }
  41978. return false;
  41979. };
  41980. ValueCondition.prototype.serialize = function () {
  41981. return this._serialize({
  41982. name: "ValueCondition",
  41983. properties: [
  41984. BABYLON.Action._GetTargetProperty(this._target),
  41985. { name: "propertyPath", value: this.propertyPath },
  41986. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  41987. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  41988. ]
  41989. });
  41990. };
  41991. ValueCondition.GetOperatorName = function (operator) {
  41992. switch (operator) {
  41993. case ValueCondition._IsEqual: return "IsEqual";
  41994. case ValueCondition._IsDifferent: return "IsDifferent";
  41995. case ValueCondition._IsGreater: return "IsGreater";
  41996. case ValueCondition._IsLesser: return "IsLesser";
  41997. default: return "";
  41998. }
  41999. };
  42000. // Statics
  42001. ValueCondition._IsEqual = 0;
  42002. ValueCondition._IsDifferent = 1;
  42003. ValueCondition._IsGreater = 2;
  42004. ValueCondition._IsLesser = 3;
  42005. return ValueCondition;
  42006. }(Condition));
  42007. BABYLON.ValueCondition = ValueCondition;
  42008. var PredicateCondition = /** @class */ (function (_super) {
  42009. __extends(PredicateCondition, _super);
  42010. function PredicateCondition(actionManager, predicate) {
  42011. var _this = _super.call(this, actionManager) || this;
  42012. _this.predicate = predicate;
  42013. return _this;
  42014. }
  42015. PredicateCondition.prototype.isValid = function () {
  42016. return this.predicate();
  42017. };
  42018. return PredicateCondition;
  42019. }(Condition));
  42020. BABYLON.PredicateCondition = PredicateCondition;
  42021. var StateCondition = /** @class */ (function (_super) {
  42022. __extends(StateCondition, _super);
  42023. function StateCondition(actionManager, target, value) {
  42024. var _this = _super.call(this, actionManager) || this;
  42025. _this.value = value;
  42026. _this._target = target;
  42027. return _this;
  42028. }
  42029. // Methods
  42030. StateCondition.prototype.isValid = function () {
  42031. return this._target.state === this.value;
  42032. };
  42033. StateCondition.prototype.serialize = function () {
  42034. return this._serialize({
  42035. name: "StateCondition",
  42036. properties: [
  42037. BABYLON.Action._GetTargetProperty(this._target),
  42038. { name: "value", value: this.value }
  42039. ]
  42040. });
  42041. };
  42042. return StateCondition;
  42043. }(Condition));
  42044. BABYLON.StateCondition = StateCondition;
  42045. })(BABYLON || (BABYLON = {}));
  42046. //# sourceMappingURL=babylon.condition.js.map
  42047. var BABYLON;
  42048. (function (BABYLON) {
  42049. var Action = /** @class */ (function () {
  42050. function Action(triggerOptions, condition) {
  42051. this.triggerOptions = triggerOptions;
  42052. this.onBeforeExecuteObservable = new BABYLON.Observable();
  42053. if (triggerOptions.parameter) {
  42054. this.trigger = triggerOptions.trigger;
  42055. this._triggerParameter = triggerOptions.parameter;
  42056. }
  42057. else {
  42058. this.trigger = triggerOptions;
  42059. }
  42060. this._nextActiveAction = this;
  42061. this._condition = condition;
  42062. }
  42063. // Methods
  42064. Action.prototype._prepare = function () {
  42065. };
  42066. Action.prototype.getTriggerParameter = function () {
  42067. return this._triggerParameter;
  42068. };
  42069. Action.prototype._executeCurrent = function (evt) {
  42070. if (this._nextActiveAction._condition) {
  42071. var condition = this._nextActiveAction._condition;
  42072. var currentRenderId = this._actionManager.getScene().getRenderId();
  42073. // We cache the current evaluation for the current frame
  42074. if (condition._evaluationId === currentRenderId) {
  42075. if (!condition._currentResult) {
  42076. return;
  42077. }
  42078. }
  42079. else {
  42080. condition._evaluationId = currentRenderId;
  42081. if (!condition.isValid()) {
  42082. condition._currentResult = false;
  42083. return;
  42084. }
  42085. condition._currentResult = true;
  42086. }
  42087. }
  42088. this.onBeforeExecuteObservable.notifyObservers(this);
  42089. this._nextActiveAction.execute(evt);
  42090. this.skipToNextActiveAction();
  42091. };
  42092. Action.prototype.execute = function (evt) {
  42093. };
  42094. Action.prototype.skipToNextActiveAction = function () {
  42095. if (this._nextActiveAction._child) {
  42096. if (!this._nextActiveAction._child._actionManager) {
  42097. this._nextActiveAction._child._actionManager = this._actionManager;
  42098. }
  42099. this._nextActiveAction = this._nextActiveAction._child;
  42100. }
  42101. else {
  42102. this._nextActiveAction = this;
  42103. }
  42104. };
  42105. Action.prototype.then = function (action) {
  42106. this._child = action;
  42107. action._actionManager = this._actionManager;
  42108. action._prepare();
  42109. return action;
  42110. };
  42111. Action.prototype._getProperty = function (propertyPath) {
  42112. return this._actionManager._getProperty(propertyPath);
  42113. };
  42114. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  42115. return this._actionManager._getEffectiveTarget(target, propertyPath);
  42116. };
  42117. Action.prototype.serialize = function (parent) {
  42118. };
  42119. // Called by BABYLON.Action objects in serialize(...). Internal use
  42120. Action.prototype._serialize = function (serializedAction, parent) {
  42121. var serializationObject = {
  42122. type: 1,
  42123. children: [],
  42124. name: serializedAction.name,
  42125. properties: serializedAction.properties || []
  42126. };
  42127. // Serialize child
  42128. if (this._child) {
  42129. this._child.serialize(serializationObject);
  42130. }
  42131. // Check if "this" has a condition
  42132. if (this._condition) {
  42133. var serializedCondition = this._condition.serialize();
  42134. serializedCondition.children.push(serializationObject);
  42135. if (parent) {
  42136. parent.children.push(serializedCondition);
  42137. }
  42138. return serializedCondition;
  42139. }
  42140. if (parent) {
  42141. parent.children.push(serializationObject);
  42142. }
  42143. return serializationObject;
  42144. };
  42145. Action._SerializeValueAsString = function (value) {
  42146. if (typeof value === "number") {
  42147. return value.toString();
  42148. }
  42149. if (typeof value === "boolean") {
  42150. return value ? "true" : "false";
  42151. }
  42152. if (value instanceof BABYLON.Vector2) {
  42153. return value.x + ", " + value.y;
  42154. }
  42155. if (value instanceof BABYLON.Vector3) {
  42156. return value.x + ", " + value.y + ", " + value.z;
  42157. }
  42158. if (value instanceof BABYLON.Color3) {
  42159. return value.r + ", " + value.g + ", " + value.b;
  42160. }
  42161. if (value instanceof BABYLON.Color4) {
  42162. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  42163. }
  42164. return value; // string
  42165. };
  42166. Action._GetTargetProperty = function (target) {
  42167. return {
  42168. name: "target",
  42169. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  42170. : target instanceof BABYLON.Light ? "LightProperties"
  42171. : target instanceof BABYLON.Camera ? "CameraProperties"
  42172. : "SceneProperties",
  42173. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  42174. };
  42175. };
  42176. return Action;
  42177. }());
  42178. BABYLON.Action = Action;
  42179. })(BABYLON || (BABYLON = {}));
  42180. //# sourceMappingURL=babylon.action.js.map
  42181. var BABYLON;
  42182. (function (BABYLON) {
  42183. /**
  42184. * ActionEvent is the event beint sent when an action is triggered.
  42185. */
  42186. var ActionEvent = /** @class */ (function () {
  42187. /**
  42188. * @param source The mesh or sprite that triggered the action.
  42189. * @param pointerX The X mouse cursor position at the time of the event
  42190. * @param pointerY The Y mouse cursor position at the time of the event
  42191. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  42192. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  42193. */
  42194. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  42195. this.source = source;
  42196. this.pointerX = pointerX;
  42197. this.pointerY = pointerY;
  42198. this.meshUnderPointer = meshUnderPointer;
  42199. this.sourceEvent = sourceEvent;
  42200. this.additionalData = additionalData;
  42201. }
  42202. /**
  42203. * Helper function to auto-create an ActionEvent from a source mesh.
  42204. * @param source The source mesh that triggered the event
  42205. * @param evt {Event} The original (browser) event
  42206. */
  42207. ActionEvent.CreateNew = function (source, evt, additionalData) {
  42208. var scene = source.getScene();
  42209. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  42210. };
  42211. /**
  42212. * Helper function to auto-create an ActionEvent from a source mesh.
  42213. * @param source The source sprite that triggered the event
  42214. * @param scene Scene associated with the sprite
  42215. * @param evt {Event} The original (browser) event
  42216. */
  42217. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  42218. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  42219. };
  42220. /**
  42221. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  42222. * @param scene the scene where the event occurred
  42223. * @param evt {Event} The original (browser) event
  42224. */
  42225. ActionEvent.CreateNewFromScene = function (scene, evt) {
  42226. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  42227. };
  42228. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  42229. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  42230. };
  42231. return ActionEvent;
  42232. }());
  42233. BABYLON.ActionEvent = ActionEvent;
  42234. /**
  42235. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  42236. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  42237. */
  42238. var ActionManager = /** @class */ (function () {
  42239. function ActionManager(scene) {
  42240. // Members
  42241. this.actions = new Array();
  42242. this.hoverCursor = '';
  42243. this._scene = scene;
  42244. scene._actionManagers.push(this);
  42245. }
  42246. Object.defineProperty(ActionManager, "NothingTrigger", {
  42247. get: function () {
  42248. return ActionManager._NothingTrigger;
  42249. },
  42250. enumerable: true,
  42251. configurable: true
  42252. });
  42253. Object.defineProperty(ActionManager, "OnPickTrigger", {
  42254. get: function () {
  42255. return ActionManager._OnPickTrigger;
  42256. },
  42257. enumerable: true,
  42258. configurable: true
  42259. });
  42260. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  42261. get: function () {
  42262. return ActionManager._OnLeftPickTrigger;
  42263. },
  42264. enumerable: true,
  42265. configurable: true
  42266. });
  42267. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  42268. get: function () {
  42269. return ActionManager._OnRightPickTrigger;
  42270. },
  42271. enumerable: true,
  42272. configurable: true
  42273. });
  42274. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  42275. get: function () {
  42276. return ActionManager._OnCenterPickTrigger;
  42277. },
  42278. enumerable: true,
  42279. configurable: true
  42280. });
  42281. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  42282. get: function () {
  42283. return ActionManager._OnPickDownTrigger;
  42284. },
  42285. enumerable: true,
  42286. configurable: true
  42287. });
  42288. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  42289. get: function () {
  42290. return ActionManager._OnDoublePickTrigger;
  42291. },
  42292. enumerable: true,
  42293. configurable: true
  42294. });
  42295. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  42296. get: function () {
  42297. return ActionManager._OnPickUpTrigger;
  42298. },
  42299. enumerable: true,
  42300. configurable: true
  42301. });
  42302. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  42303. /// This trigger will only be raised if you also declared a OnPickDown
  42304. get: function () {
  42305. return ActionManager._OnPickOutTrigger;
  42306. },
  42307. enumerable: true,
  42308. configurable: true
  42309. });
  42310. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  42311. get: function () {
  42312. return ActionManager._OnLongPressTrigger;
  42313. },
  42314. enumerable: true,
  42315. configurable: true
  42316. });
  42317. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  42318. get: function () {
  42319. return ActionManager._OnPointerOverTrigger;
  42320. },
  42321. enumerable: true,
  42322. configurable: true
  42323. });
  42324. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  42325. get: function () {
  42326. return ActionManager._OnPointerOutTrigger;
  42327. },
  42328. enumerable: true,
  42329. configurable: true
  42330. });
  42331. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  42332. get: function () {
  42333. return ActionManager._OnEveryFrameTrigger;
  42334. },
  42335. enumerable: true,
  42336. configurable: true
  42337. });
  42338. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  42339. get: function () {
  42340. return ActionManager._OnIntersectionEnterTrigger;
  42341. },
  42342. enumerable: true,
  42343. configurable: true
  42344. });
  42345. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  42346. get: function () {
  42347. return ActionManager._OnIntersectionExitTrigger;
  42348. },
  42349. enumerable: true,
  42350. configurable: true
  42351. });
  42352. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  42353. get: function () {
  42354. return ActionManager._OnKeyDownTrigger;
  42355. },
  42356. enumerable: true,
  42357. configurable: true
  42358. });
  42359. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  42360. get: function () {
  42361. return ActionManager._OnKeyUpTrigger;
  42362. },
  42363. enumerable: true,
  42364. configurable: true
  42365. });
  42366. // Methods
  42367. ActionManager.prototype.dispose = function () {
  42368. var index = this._scene._actionManagers.indexOf(this);
  42369. for (var i = 0; i < this.actions.length; i++) {
  42370. var action = this.actions[i];
  42371. ActionManager.Triggers[action.trigger]--;
  42372. if (ActionManager.Triggers[action.trigger] === 0) {
  42373. delete ActionManager.Triggers[action.trigger];
  42374. }
  42375. }
  42376. if (index > -1) {
  42377. this._scene._actionManagers.splice(index, 1);
  42378. }
  42379. };
  42380. ActionManager.prototype.getScene = function () {
  42381. return this._scene;
  42382. };
  42383. /**
  42384. * Does this action manager handles actions of any of the given triggers
  42385. * @param {number[]} triggers - the triggers to be tested
  42386. * @return {boolean} whether one (or more) of the triggers is handeled
  42387. */
  42388. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  42389. for (var index = 0; index < this.actions.length; index++) {
  42390. var action = this.actions[index];
  42391. if (triggers.indexOf(action.trigger) > -1) {
  42392. return true;
  42393. }
  42394. }
  42395. return false;
  42396. };
  42397. /**
  42398. * Does this action manager handles actions of a given trigger
  42399. * @param {number} trigger - the trigger to be tested
  42400. * @return {boolean} whether the trigger is handeled
  42401. */
  42402. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  42403. for (var index = 0; index < this.actions.length; index++) {
  42404. var action = this.actions[index];
  42405. if (action.trigger === trigger) {
  42406. return true;
  42407. }
  42408. }
  42409. return false;
  42410. };
  42411. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  42412. /**
  42413. * Does this action manager has pointer triggers
  42414. * @return {boolean} whether or not it has pointer triggers
  42415. */
  42416. get: function () {
  42417. for (var index = 0; index < this.actions.length; index++) {
  42418. var action = this.actions[index];
  42419. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  42420. return true;
  42421. }
  42422. }
  42423. return false;
  42424. },
  42425. enumerable: true,
  42426. configurable: true
  42427. });
  42428. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  42429. /**
  42430. * Does this action manager has pick triggers
  42431. * @return {boolean} whether or not it has pick triggers
  42432. */
  42433. get: function () {
  42434. for (var index = 0; index < this.actions.length; index++) {
  42435. var action = this.actions[index];
  42436. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  42437. return true;
  42438. }
  42439. }
  42440. return false;
  42441. },
  42442. enumerable: true,
  42443. configurable: true
  42444. });
  42445. Object.defineProperty(ActionManager, "HasTriggers", {
  42446. /**
  42447. * Does exist one action manager with at least one trigger
  42448. * @return {boolean} whether or not it exists one action manager with one trigger
  42449. **/
  42450. get: function () {
  42451. for (var t in ActionManager.Triggers) {
  42452. if (ActionManager.Triggers.hasOwnProperty(t)) {
  42453. return true;
  42454. }
  42455. }
  42456. return false;
  42457. },
  42458. enumerable: true,
  42459. configurable: true
  42460. });
  42461. Object.defineProperty(ActionManager, "HasPickTriggers", {
  42462. /**
  42463. * Does exist one action manager with at least one pick trigger
  42464. * @return {boolean} whether or not it exists one action manager with one pick trigger
  42465. **/
  42466. get: function () {
  42467. for (var t in ActionManager.Triggers) {
  42468. if (ActionManager.Triggers.hasOwnProperty(t)) {
  42469. var t_int = parseInt(t);
  42470. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  42471. return true;
  42472. }
  42473. }
  42474. }
  42475. return false;
  42476. },
  42477. enumerable: true,
  42478. configurable: true
  42479. });
  42480. /**
  42481. * Does exist one action manager that handles actions of a given trigger
  42482. * @param {number} trigger - the trigger to be tested
  42483. * @return {boolean} whether the trigger is handeled by at least one action manager
  42484. **/
  42485. ActionManager.HasSpecificTrigger = function (trigger) {
  42486. for (var t in ActionManager.Triggers) {
  42487. if (ActionManager.Triggers.hasOwnProperty(t)) {
  42488. var t_int = parseInt(t);
  42489. if (t_int === trigger) {
  42490. return true;
  42491. }
  42492. }
  42493. }
  42494. return false;
  42495. };
  42496. /**
  42497. * Registers an action to this action manager
  42498. * @param {BABYLON.Action} action - the action to be registered
  42499. * @return {BABYLON.Action} the action amended (prepared) after registration
  42500. */
  42501. ActionManager.prototype.registerAction = function (action) {
  42502. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  42503. if (this.getScene().actionManager !== this) {
  42504. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  42505. return null;
  42506. }
  42507. }
  42508. this.actions.push(action);
  42509. if (ActionManager.Triggers[action.trigger]) {
  42510. ActionManager.Triggers[action.trigger]++;
  42511. }
  42512. else {
  42513. ActionManager.Triggers[action.trigger] = 1;
  42514. }
  42515. action._actionManager = this;
  42516. action._prepare();
  42517. return action;
  42518. };
  42519. /**
  42520. * Process a specific trigger
  42521. * @param {number} trigger - the trigger to process
  42522. * @param evt {BABYLON.ActionEvent} the event details to be processed
  42523. */
  42524. ActionManager.prototype.processTrigger = function (trigger, evt) {
  42525. for (var index = 0; index < this.actions.length; index++) {
  42526. var action = this.actions[index];
  42527. if (action.trigger === trigger) {
  42528. if (evt) {
  42529. if (trigger === ActionManager.OnKeyUpTrigger
  42530. || trigger === ActionManager.OnKeyDownTrigger) {
  42531. var parameter = action.getTriggerParameter();
  42532. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  42533. if (!parameter.toLowerCase) {
  42534. continue;
  42535. }
  42536. var lowerCase = parameter.toLowerCase();
  42537. if (lowerCase !== evt.sourceEvent.key) {
  42538. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  42539. var actualkey = String.fromCharCode(unicode).toLowerCase();
  42540. if (actualkey !== lowerCase) {
  42541. continue;
  42542. }
  42543. }
  42544. }
  42545. }
  42546. }
  42547. action._executeCurrent(evt);
  42548. }
  42549. }
  42550. };
  42551. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  42552. var properties = propertyPath.split(".");
  42553. for (var index = 0; index < properties.length - 1; index++) {
  42554. target = target[properties[index]];
  42555. }
  42556. return target;
  42557. };
  42558. ActionManager.prototype._getProperty = function (propertyPath) {
  42559. var properties = propertyPath.split(".");
  42560. return properties[properties.length - 1];
  42561. };
  42562. ActionManager.prototype.serialize = function (name) {
  42563. var root = {
  42564. children: new Array(),
  42565. name: name,
  42566. type: 3,
  42567. properties: new Array() // Empty for root but required
  42568. };
  42569. for (var i = 0; i < this.actions.length; i++) {
  42570. var triggerObject = {
  42571. type: 0,
  42572. children: new Array(),
  42573. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  42574. properties: new Array()
  42575. };
  42576. var triggerOptions = this.actions[i].triggerOptions;
  42577. if (triggerOptions && typeof triggerOptions !== "number") {
  42578. if (triggerOptions.parameter instanceof BABYLON.Node) {
  42579. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  42580. }
  42581. else {
  42582. var parameter = {};
  42583. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  42584. if (triggerOptions.parameter.mesh) {
  42585. parameter._meshId = triggerOptions.parameter.mesh.id;
  42586. }
  42587. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  42588. }
  42589. }
  42590. // Serialize child action, recursively
  42591. this.actions[i].serialize(triggerObject);
  42592. // Add serialized trigger
  42593. root.children.push(triggerObject);
  42594. }
  42595. return root;
  42596. };
  42597. ActionManager.Parse = function (parsedActions, object, scene) {
  42598. var actionManager = new BABYLON.ActionManager(scene);
  42599. if (object === null)
  42600. scene.actionManager = actionManager;
  42601. else
  42602. object.actionManager = actionManager;
  42603. // instanciate a new object
  42604. var instanciate = function (name, params) {
  42605. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  42606. newInstance.constructor.apply(newInstance, params);
  42607. return newInstance;
  42608. };
  42609. var parseParameter = function (name, value, target, propertyPath) {
  42610. if (propertyPath === null) {
  42611. // String, boolean or float
  42612. var floatValue = parseFloat(value);
  42613. if (value === "true" || value === "false")
  42614. return value === "true";
  42615. else
  42616. return isNaN(floatValue) ? value : floatValue;
  42617. }
  42618. var effectiveTarget = propertyPath.split(".");
  42619. var values = value.split(",");
  42620. // Get effective Target
  42621. for (var i = 0; i < effectiveTarget.length; i++) {
  42622. target = target[effectiveTarget[i]];
  42623. }
  42624. // Return appropriate value with its type
  42625. if (typeof (target) === "boolean")
  42626. return values[0] === "true";
  42627. if (typeof (target) === "string")
  42628. return values[0];
  42629. // Parameters with multiple values such as Vector3 etc.
  42630. var split = new Array();
  42631. for (var i = 0; i < values.length; i++)
  42632. split.push(parseFloat(values[i]));
  42633. if (target instanceof BABYLON.Vector3)
  42634. return BABYLON.Vector3.FromArray(split);
  42635. if (target instanceof BABYLON.Vector4)
  42636. return BABYLON.Vector4.FromArray(split);
  42637. if (target instanceof BABYLON.Color3)
  42638. return BABYLON.Color3.FromArray(split);
  42639. if (target instanceof BABYLON.Color4)
  42640. return BABYLON.Color4.FromArray(split);
  42641. return parseFloat(values[0]);
  42642. };
  42643. // traverse graph per trigger
  42644. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  42645. if (combineArray === void 0) { combineArray = null; }
  42646. if (parsedAction.detached)
  42647. return;
  42648. var parameters = new Array();
  42649. var target = null;
  42650. var propertyPath = null;
  42651. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  42652. // Parameters
  42653. if (parsedAction.type === 2)
  42654. parameters.push(actionManager);
  42655. else
  42656. parameters.push(trigger);
  42657. if (combine) {
  42658. var actions = new Array();
  42659. for (var j = 0; j < parsedAction.combine.length; j++) {
  42660. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  42661. }
  42662. parameters.push(actions);
  42663. }
  42664. else {
  42665. for (var i = 0; i < parsedAction.properties.length; i++) {
  42666. var value = parsedAction.properties[i].value;
  42667. var name = parsedAction.properties[i].name;
  42668. var targetType = parsedAction.properties[i].targetType;
  42669. if (name === "target")
  42670. if (targetType !== null && targetType === "SceneProperties")
  42671. value = target = scene;
  42672. else
  42673. value = target = scene.getNodeByName(value);
  42674. else if (name === "parent")
  42675. value = scene.getNodeByName(value);
  42676. else if (name === "sound")
  42677. value = scene.getSoundByName(value);
  42678. else if (name !== "propertyPath") {
  42679. if (parsedAction.type === 2 && name === "operator")
  42680. value = BABYLON.ValueCondition[value];
  42681. else
  42682. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  42683. }
  42684. else {
  42685. propertyPath = value;
  42686. }
  42687. parameters.push(value);
  42688. }
  42689. }
  42690. if (combineArray === null) {
  42691. parameters.push(condition);
  42692. }
  42693. else {
  42694. parameters.push(null);
  42695. }
  42696. // If interpolate value action
  42697. if (parsedAction.name === "InterpolateValueAction") {
  42698. var param = parameters[parameters.length - 2];
  42699. parameters[parameters.length - 1] = param;
  42700. parameters[parameters.length - 2] = condition;
  42701. }
  42702. // Action or condition(s) and not CombineAction
  42703. var newAction = instanciate(parsedAction.name, parameters);
  42704. if (newAction instanceof BABYLON.Condition && condition !== null) {
  42705. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  42706. if (action)
  42707. action.then(nothing);
  42708. else
  42709. actionManager.registerAction(nothing);
  42710. action = nothing;
  42711. }
  42712. if (combineArray === null) {
  42713. if (newAction instanceof BABYLON.Condition) {
  42714. condition = newAction;
  42715. newAction = action;
  42716. }
  42717. else {
  42718. condition = null;
  42719. if (action)
  42720. action.then(newAction);
  42721. else
  42722. actionManager.registerAction(newAction);
  42723. }
  42724. }
  42725. else {
  42726. combineArray.push(newAction);
  42727. }
  42728. for (var i = 0; i < parsedAction.children.length; i++)
  42729. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  42730. };
  42731. // triggers
  42732. for (var i = 0; i < parsedActions.children.length; i++) {
  42733. var triggerParams;
  42734. var trigger = parsedActions.children[i];
  42735. if (trigger.properties.length > 0) {
  42736. var param = trigger.properties[0].value;
  42737. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  42738. if (value._meshId) {
  42739. value.mesh = scene.getMeshByID(value._meshId);
  42740. }
  42741. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  42742. }
  42743. else
  42744. triggerParams = ActionManager[trigger.name];
  42745. for (var j = 0; j < trigger.children.length; j++) {
  42746. if (!trigger.detached)
  42747. traverse(trigger.children[j], triggerParams, null, null);
  42748. }
  42749. }
  42750. };
  42751. ActionManager.GetTriggerName = function (trigger) {
  42752. switch (trigger) {
  42753. case 0: return "NothingTrigger";
  42754. case 1: return "OnPickTrigger";
  42755. case 2: return "OnLeftPickTrigger";
  42756. case 3: return "OnRightPickTrigger";
  42757. case 4: return "OnCenterPickTrigger";
  42758. case 5: return "OnPickDownTrigger";
  42759. case 6: return "OnPickUpTrigger";
  42760. case 7: return "OnLongPressTrigger";
  42761. case 8: return "OnPointerOverTrigger";
  42762. case 9: return "OnPointerOutTrigger";
  42763. case 10: return "OnEveryFrameTrigger";
  42764. case 11: return "OnIntersectionEnterTrigger";
  42765. case 12: return "OnIntersectionExitTrigger";
  42766. case 13: return "OnKeyDownTrigger";
  42767. case 14: return "OnKeyUpTrigger";
  42768. case 15: return "OnPickOutTrigger";
  42769. default: return "";
  42770. }
  42771. };
  42772. // Statics
  42773. ActionManager._NothingTrigger = 0;
  42774. ActionManager._OnPickTrigger = 1;
  42775. ActionManager._OnLeftPickTrigger = 2;
  42776. ActionManager._OnRightPickTrigger = 3;
  42777. ActionManager._OnCenterPickTrigger = 4;
  42778. ActionManager._OnPickDownTrigger = 5;
  42779. ActionManager._OnDoublePickTrigger = 6;
  42780. ActionManager._OnPickUpTrigger = 7;
  42781. ActionManager._OnLongPressTrigger = 8;
  42782. ActionManager._OnPointerOverTrigger = 9;
  42783. ActionManager._OnPointerOutTrigger = 10;
  42784. ActionManager._OnEveryFrameTrigger = 11;
  42785. ActionManager._OnIntersectionEnterTrigger = 12;
  42786. ActionManager._OnIntersectionExitTrigger = 13;
  42787. ActionManager._OnKeyDownTrigger = 14;
  42788. ActionManager._OnKeyUpTrigger = 15;
  42789. ActionManager._OnPickOutTrigger = 16;
  42790. ActionManager.Triggers = {};
  42791. return ActionManager;
  42792. }());
  42793. BABYLON.ActionManager = ActionManager;
  42794. })(BABYLON || (BABYLON = {}));
  42795. //# sourceMappingURL=babylon.actionManager.js.map
  42796. var BABYLON;
  42797. (function (BABYLON) {
  42798. var InterpolateValueAction = /** @class */ (function (_super) {
  42799. __extends(InterpolateValueAction, _super);
  42800. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  42801. if (duration === void 0) { duration = 1000; }
  42802. var _this = _super.call(this, triggerOptions, condition) || this;
  42803. _this.propertyPath = propertyPath;
  42804. _this.value = value;
  42805. _this.duration = duration;
  42806. _this.stopOtherAnimations = stopOtherAnimations;
  42807. _this.onInterpolationDone = onInterpolationDone;
  42808. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  42809. _this._target = _this._effectiveTarget = target;
  42810. return _this;
  42811. }
  42812. InterpolateValueAction.prototype._prepare = function () {
  42813. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42814. this._property = this._getProperty(this.propertyPath);
  42815. };
  42816. InterpolateValueAction.prototype.execute = function () {
  42817. var _this = this;
  42818. var scene = this._actionManager.getScene();
  42819. var keys = [
  42820. {
  42821. frame: 0,
  42822. value: this._effectiveTarget[this._property]
  42823. }, {
  42824. frame: 100,
  42825. value: this.value
  42826. }
  42827. ];
  42828. var dataType;
  42829. if (typeof this.value === "number") {
  42830. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  42831. }
  42832. else if (this.value instanceof BABYLON.Color3) {
  42833. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  42834. }
  42835. else if (this.value instanceof BABYLON.Vector3) {
  42836. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  42837. }
  42838. else if (this.value instanceof BABYLON.Matrix) {
  42839. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  42840. }
  42841. else if (this.value instanceof BABYLON.Quaternion) {
  42842. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  42843. }
  42844. else {
  42845. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  42846. return;
  42847. }
  42848. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  42849. animation.setKeys(keys);
  42850. if (this.stopOtherAnimations) {
  42851. scene.stopAnimation(this._effectiveTarget);
  42852. }
  42853. var wrapper = function () {
  42854. _this.onInterpolationDoneObservable.notifyObservers(_this);
  42855. if (_this.onInterpolationDone) {
  42856. _this.onInterpolationDone();
  42857. }
  42858. };
  42859. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  42860. };
  42861. InterpolateValueAction.prototype.serialize = function (parent) {
  42862. return _super.prototype._serialize.call(this, {
  42863. name: "InterpolateValueAction",
  42864. properties: [
  42865. BABYLON.Action._GetTargetProperty(this._target),
  42866. { name: "propertyPath", value: this.propertyPath },
  42867. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  42868. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  42869. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  42870. ]
  42871. }, parent);
  42872. };
  42873. return InterpolateValueAction;
  42874. }(BABYLON.Action));
  42875. BABYLON.InterpolateValueAction = InterpolateValueAction;
  42876. })(BABYLON || (BABYLON = {}));
  42877. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  42878. var BABYLON;
  42879. (function (BABYLON) {
  42880. var SwitchBooleanAction = /** @class */ (function (_super) {
  42881. __extends(SwitchBooleanAction, _super);
  42882. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  42883. var _this = _super.call(this, triggerOptions, condition) || this;
  42884. _this.propertyPath = propertyPath;
  42885. _this._target = _this._effectiveTarget = target;
  42886. return _this;
  42887. }
  42888. SwitchBooleanAction.prototype._prepare = function () {
  42889. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42890. this._property = this._getProperty(this.propertyPath);
  42891. };
  42892. SwitchBooleanAction.prototype.execute = function () {
  42893. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  42894. };
  42895. SwitchBooleanAction.prototype.serialize = function (parent) {
  42896. return _super.prototype._serialize.call(this, {
  42897. name: "SwitchBooleanAction",
  42898. properties: [
  42899. BABYLON.Action._GetTargetProperty(this._target),
  42900. { name: "propertyPath", value: this.propertyPath }
  42901. ]
  42902. }, parent);
  42903. };
  42904. return SwitchBooleanAction;
  42905. }(BABYLON.Action));
  42906. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  42907. var SetStateAction = /** @class */ (function (_super) {
  42908. __extends(SetStateAction, _super);
  42909. function SetStateAction(triggerOptions, target, value, condition) {
  42910. var _this = _super.call(this, triggerOptions, condition) || this;
  42911. _this.value = value;
  42912. _this._target = target;
  42913. return _this;
  42914. }
  42915. SetStateAction.prototype.execute = function () {
  42916. this._target.state = this.value;
  42917. };
  42918. SetStateAction.prototype.serialize = function (parent) {
  42919. return _super.prototype._serialize.call(this, {
  42920. name: "SetStateAction",
  42921. properties: [
  42922. BABYLON.Action._GetTargetProperty(this._target),
  42923. { name: "value", value: this.value }
  42924. ]
  42925. }, parent);
  42926. };
  42927. return SetStateAction;
  42928. }(BABYLON.Action));
  42929. BABYLON.SetStateAction = SetStateAction;
  42930. var SetValueAction = /** @class */ (function (_super) {
  42931. __extends(SetValueAction, _super);
  42932. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  42933. var _this = _super.call(this, triggerOptions, condition) || this;
  42934. _this.propertyPath = propertyPath;
  42935. _this.value = value;
  42936. _this._target = _this._effectiveTarget = target;
  42937. return _this;
  42938. }
  42939. SetValueAction.prototype._prepare = function () {
  42940. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42941. this._property = this._getProperty(this.propertyPath);
  42942. };
  42943. SetValueAction.prototype.execute = function () {
  42944. this._effectiveTarget[this._property] = this.value;
  42945. if (this._target.markAsDirty) {
  42946. this._target.markAsDirty(this._property);
  42947. }
  42948. };
  42949. SetValueAction.prototype.serialize = function (parent) {
  42950. return _super.prototype._serialize.call(this, {
  42951. name: "SetValueAction",
  42952. properties: [
  42953. BABYLON.Action._GetTargetProperty(this._target),
  42954. { name: "propertyPath", value: this.propertyPath },
  42955. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  42956. ]
  42957. }, parent);
  42958. };
  42959. return SetValueAction;
  42960. }(BABYLON.Action));
  42961. BABYLON.SetValueAction = SetValueAction;
  42962. var IncrementValueAction = /** @class */ (function (_super) {
  42963. __extends(IncrementValueAction, _super);
  42964. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  42965. var _this = _super.call(this, triggerOptions, condition) || this;
  42966. _this.propertyPath = propertyPath;
  42967. _this.value = value;
  42968. _this._target = _this._effectiveTarget = target;
  42969. return _this;
  42970. }
  42971. IncrementValueAction.prototype._prepare = function () {
  42972. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42973. this._property = this._getProperty(this.propertyPath);
  42974. if (typeof this._effectiveTarget[this._property] !== "number") {
  42975. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  42976. }
  42977. };
  42978. IncrementValueAction.prototype.execute = function () {
  42979. this._effectiveTarget[this._property] += this.value;
  42980. if (this._target.markAsDirty) {
  42981. this._target.markAsDirty(this._property);
  42982. }
  42983. };
  42984. IncrementValueAction.prototype.serialize = function (parent) {
  42985. return _super.prototype._serialize.call(this, {
  42986. name: "IncrementValueAction",
  42987. properties: [
  42988. BABYLON.Action._GetTargetProperty(this._target),
  42989. { name: "propertyPath", value: this.propertyPath },
  42990. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  42991. ]
  42992. }, parent);
  42993. };
  42994. return IncrementValueAction;
  42995. }(BABYLON.Action));
  42996. BABYLON.IncrementValueAction = IncrementValueAction;
  42997. var PlayAnimationAction = /** @class */ (function (_super) {
  42998. __extends(PlayAnimationAction, _super);
  42999. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  43000. var _this = _super.call(this, triggerOptions, condition) || this;
  43001. _this.from = from;
  43002. _this.to = to;
  43003. _this.loop = loop;
  43004. _this._target = target;
  43005. return _this;
  43006. }
  43007. PlayAnimationAction.prototype._prepare = function () {
  43008. };
  43009. PlayAnimationAction.prototype.execute = function () {
  43010. var scene = this._actionManager.getScene();
  43011. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  43012. };
  43013. PlayAnimationAction.prototype.serialize = function (parent) {
  43014. return _super.prototype._serialize.call(this, {
  43015. name: "PlayAnimationAction",
  43016. properties: [
  43017. BABYLON.Action._GetTargetProperty(this._target),
  43018. { name: "from", value: String(this.from) },
  43019. { name: "to", value: String(this.to) },
  43020. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  43021. ]
  43022. }, parent);
  43023. };
  43024. return PlayAnimationAction;
  43025. }(BABYLON.Action));
  43026. BABYLON.PlayAnimationAction = PlayAnimationAction;
  43027. var StopAnimationAction = /** @class */ (function (_super) {
  43028. __extends(StopAnimationAction, _super);
  43029. function StopAnimationAction(triggerOptions, target, condition) {
  43030. var _this = _super.call(this, triggerOptions, condition) || this;
  43031. _this._target = target;
  43032. return _this;
  43033. }
  43034. StopAnimationAction.prototype._prepare = function () {
  43035. };
  43036. StopAnimationAction.prototype.execute = function () {
  43037. var scene = this._actionManager.getScene();
  43038. scene.stopAnimation(this._target);
  43039. };
  43040. StopAnimationAction.prototype.serialize = function (parent) {
  43041. return _super.prototype._serialize.call(this, {
  43042. name: "StopAnimationAction",
  43043. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  43044. }, parent);
  43045. };
  43046. return StopAnimationAction;
  43047. }(BABYLON.Action));
  43048. BABYLON.StopAnimationAction = StopAnimationAction;
  43049. var DoNothingAction = /** @class */ (function (_super) {
  43050. __extends(DoNothingAction, _super);
  43051. function DoNothingAction(triggerOptions, condition) {
  43052. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  43053. return _super.call(this, triggerOptions, condition) || this;
  43054. }
  43055. DoNothingAction.prototype.execute = function () {
  43056. };
  43057. DoNothingAction.prototype.serialize = function (parent) {
  43058. return _super.prototype._serialize.call(this, {
  43059. name: "DoNothingAction",
  43060. properties: []
  43061. }, parent);
  43062. };
  43063. return DoNothingAction;
  43064. }(BABYLON.Action));
  43065. BABYLON.DoNothingAction = DoNothingAction;
  43066. var CombineAction = /** @class */ (function (_super) {
  43067. __extends(CombineAction, _super);
  43068. function CombineAction(triggerOptions, children, condition) {
  43069. var _this = _super.call(this, triggerOptions, condition) || this;
  43070. _this.children = children;
  43071. return _this;
  43072. }
  43073. CombineAction.prototype._prepare = function () {
  43074. for (var index = 0; index < this.children.length; index++) {
  43075. this.children[index]._actionManager = this._actionManager;
  43076. this.children[index]._prepare();
  43077. }
  43078. };
  43079. CombineAction.prototype.execute = function (evt) {
  43080. for (var index = 0; index < this.children.length; index++) {
  43081. this.children[index].execute(evt);
  43082. }
  43083. };
  43084. CombineAction.prototype.serialize = function (parent) {
  43085. var serializationObject = _super.prototype._serialize.call(this, {
  43086. name: "CombineAction",
  43087. properties: [],
  43088. combine: []
  43089. }, parent);
  43090. for (var i = 0; i < this.children.length; i++) {
  43091. serializationObject.combine.push(this.children[i].serialize(null));
  43092. }
  43093. return serializationObject;
  43094. };
  43095. return CombineAction;
  43096. }(BABYLON.Action));
  43097. BABYLON.CombineAction = CombineAction;
  43098. var ExecuteCodeAction = /** @class */ (function (_super) {
  43099. __extends(ExecuteCodeAction, _super);
  43100. function ExecuteCodeAction(triggerOptions, func, condition) {
  43101. var _this = _super.call(this, triggerOptions, condition) || this;
  43102. _this.func = func;
  43103. return _this;
  43104. }
  43105. ExecuteCodeAction.prototype.execute = function (evt) {
  43106. this.func(evt);
  43107. };
  43108. return ExecuteCodeAction;
  43109. }(BABYLON.Action));
  43110. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  43111. var SetParentAction = /** @class */ (function (_super) {
  43112. __extends(SetParentAction, _super);
  43113. function SetParentAction(triggerOptions, target, parent, condition) {
  43114. var _this = _super.call(this, triggerOptions, condition) || this;
  43115. _this._target = target;
  43116. _this._parent = parent;
  43117. return _this;
  43118. }
  43119. SetParentAction.prototype._prepare = function () {
  43120. };
  43121. SetParentAction.prototype.execute = function () {
  43122. if (this._target.parent === this._parent) {
  43123. return;
  43124. }
  43125. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  43126. invertParentWorldMatrix.invert();
  43127. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  43128. this._target.parent = this._parent;
  43129. };
  43130. SetParentAction.prototype.serialize = function (parent) {
  43131. return _super.prototype._serialize.call(this, {
  43132. name: "SetParentAction",
  43133. properties: [
  43134. BABYLON.Action._GetTargetProperty(this._target),
  43135. BABYLON.Action._GetTargetProperty(this._parent),
  43136. ]
  43137. }, parent);
  43138. };
  43139. return SetParentAction;
  43140. }(BABYLON.Action));
  43141. BABYLON.SetParentAction = SetParentAction;
  43142. var PlaySoundAction = /** @class */ (function (_super) {
  43143. __extends(PlaySoundAction, _super);
  43144. function PlaySoundAction(triggerOptions, sound, condition) {
  43145. var _this = _super.call(this, triggerOptions, condition) || this;
  43146. _this._sound = sound;
  43147. return _this;
  43148. }
  43149. PlaySoundAction.prototype._prepare = function () {
  43150. };
  43151. PlaySoundAction.prototype.execute = function () {
  43152. if (this._sound !== undefined)
  43153. this._sound.play();
  43154. };
  43155. PlaySoundAction.prototype.serialize = function (parent) {
  43156. return _super.prototype._serialize.call(this, {
  43157. name: "PlaySoundAction",
  43158. properties: [{ name: "sound", value: this._sound.name }]
  43159. }, parent);
  43160. };
  43161. return PlaySoundAction;
  43162. }(BABYLON.Action));
  43163. BABYLON.PlaySoundAction = PlaySoundAction;
  43164. var StopSoundAction = /** @class */ (function (_super) {
  43165. __extends(StopSoundAction, _super);
  43166. function StopSoundAction(triggerOptions, sound, condition) {
  43167. var _this = _super.call(this, triggerOptions, condition) || this;
  43168. _this._sound = sound;
  43169. return _this;
  43170. }
  43171. StopSoundAction.prototype._prepare = function () {
  43172. };
  43173. StopSoundAction.prototype.execute = function () {
  43174. if (this._sound !== undefined)
  43175. this._sound.stop();
  43176. };
  43177. StopSoundAction.prototype.serialize = function (parent) {
  43178. return _super.prototype._serialize.call(this, {
  43179. name: "StopSoundAction",
  43180. properties: [{ name: "sound", value: this._sound.name }]
  43181. }, parent);
  43182. };
  43183. return StopSoundAction;
  43184. }(BABYLON.Action));
  43185. BABYLON.StopSoundAction = StopSoundAction;
  43186. })(BABYLON || (BABYLON = {}));
  43187. //# sourceMappingURL=babylon.directActions.js.map
  43188. var BABYLON;
  43189. (function (BABYLON) {
  43190. var SpriteManager = /** @class */ (function () {
  43191. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  43192. if (epsilon === void 0) { epsilon = 0.01; }
  43193. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43194. this.name = name;
  43195. this.sprites = new Array();
  43196. this.renderingGroupId = 0;
  43197. this.layerMask = 0x0FFFFFFF;
  43198. this.fogEnabled = true;
  43199. this.isPickable = false;
  43200. /**
  43201. * An event triggered when the manager is disposed.
  43202. * @type {BABYLON.Observable}
  43203. */
  43204. this.onDisposeObservable = new BABYLON.Observable();
  43205. this._vertexBuffers = {};
  43206. this._capacity = capacity;
  43207. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  43208. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43209. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43210. if (cellSize.width && cellSize.height) {
  43211. this.cellWidth = cellSize.width;
  43212. this.cellHeight = cellSize.height;
  43213. }
  43214. else if (cellSize !== undefined) {
  43215. this.cellWidth = cellSize;
  43216. this.cellHeight = cellSize;
  43217. }
  43218. else {
  43219. return;
  43220. }
  43221. this._epsilon = epsilon;
  43222. this._scene = scene;
  43223. this._scene.spriteManagers.push(this);
  43224. var indices = [];
  43225. var index = 0;
  43226. for (var count = 0; count < capacity; count++) {
  43227. indices.push(index);
  43228. indices.push(index + 1);
  43229. indices.push(index + 2);
  43230. indices.push(index);
  43231. indices.push(index + 2);
  43232. indices.push(index + 3);
  43233. index += 4;
  43234. }
  43235. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  43236. // VBO
  43237. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  43238. this._vertexData = new Float32Array(capacity * 16 * 4);
  43239. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  43240. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  43241. var options = this._buffer.createVertexBuffer("options", 4, 4);
  43242. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  43243. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  43244. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  43245. this._vertexBuffers["options"] = options;
  43246. this._vertexBuffers["cellInfo"] = cellInfo;
  43247. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  43248. // Effects
  43249. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  43250. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  43251. }
  43252. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  43253. set: function (callback) {
  43254. if (this._onDisposeObserver) {
  43255. this.onDisposeObservable.remove(this._onDisposeObserver);
  43256. }
  43257. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  43258. },
  43259. enumerable: true,
  43260. configurable: true
  43261. });
  43262. Object.defineProperty(SpriteManager.prototype, "texture", {
  43263. get: function () {
  43264. return this._spriteTexture;
  43265. },
  43266. set: function (value) {
  43267. this._spriteTexture = value;
  43268. },
  43269. enumerable: true,
  43270. configurable: true
  43271. });
  43272. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  43273. var arrayOffset = index * 16;
  43274. if (offsetX === 0)
  43275. offsetX = this._epsilon;
  43276. else if (offsetX === 1)
  43277. offsetX = 1 - this._epsilon;
  43278. if (offsetY === 0)
  43279. offsetY = this._epsilon;
  43280. else if (offsetY === 1)
  43281. offsetY = 1 - this._epsilon;
  43282. this._vertexData[arrayOffset] = sprite.position.x;
  43283. this._vertexData[arrayOffset + 1] = sprite.position.y;
  43284. this._vertexData[arrayOffset + 2] = sprite.position.z;
  43285. this._vertexData[arrayOffset + 3] = sprite.angle;
  43286. this._vertexData[arrayOffset + 4] = sprite.width;
  43287. this._vertexData[arrayOffset + 5] = sprite.height;
  43288. this._vertexData[arrayOffset + 6] = offsetX;
  43289. this._vertexData[arrayOffset + 7] = offsetY;
  43290. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  43291. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  43292. var offset = (sprite.cellIndex / rowSize) >> 0;
  43293. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  43294. this._vertexData[arrayOffset + 11] = offset;
  43295. // Color
  43296. this._vertexData[arrayOffset + 12] = sprite.color.r;
  43297. this._vertexData[arrayOffset + 13] = sprite.color.g;
  43298. this._vertexData[arrayOffset + 14] = sprite.color.b;
  43299. this._vertexData[arrayOffset + 15] = sprite.color.a;
  43300. };
  43301. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  43302. var count = Math.min(this._capacity, this.sprites.length);
  43303. var min = BABYLON.Vector3.Zero();
  43304. var max = BABYLON.Vector3.Zero();
  43305. var distance = Number.MAX_VALUE;
  43306. var currentSprite = null;
  43307. var cameraSpacePosition = BABYLON.Vector3.Zero();
  43308. var cameraView = camera.getViewMatrix();
  43309. for (var index = 0; index < count; index++) {
  43310. var sprite = this.sprites[index];
  43311. if (!sprite) {
  43312. continue;
  43313. }
  43314. if (predicate) {
  43315. if (!predicate(sprite)) {
  43316. continue;
  43317. }
  43318. }
  43319. else if (!sprite.isPickable) {
  43320. continue;
  43321. }
  43322. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  43323. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  43324. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  43325. if (ray.intersectsBoxMinMax(min, max)) {
  43326. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  43327. if (distance > currentDistance) {
  43328. distance = currentDistance;
  43329. currentSprite = sprite;
  43330. if (fastCheck) {
  43331. break;
  43332. }
  43333. }
  43334. }
  43335. }
  43336. if (currentSprite) {
  43337. var result = new BABYLON.PickingInfo();
  43338. result.hit = true;
  43339. result.pickedSprite = currentSprite;
  43340. result.distance = distance;
  43341. return result;
  43342. }
  43343. return null;
  43344. };
  43345. SpriteManager.prototype.render = function () {
  43346. // Check
  43347. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  43348. return;
  43349. var engine = this._scene.getEngine();
  43350. var baseSize = this._spriteTexture.getBaseSize();
  43351. // Sprites
  43352. var deltaTime = engine.getDeltaTime();
  43353. var max = Math.min(this._capacity, this.sprites.length);
  43354. var rowSize = baseSize.width / this.cellWidth;
  43355. var offset = 0;
  43356. for (var index = 0; index < max; index++) {
  43357. var sprite = this.sprites[index];
  43358. if (!sprite) {
  43359. continue;
  43360. }
  43361. sprite._animate(deltaTime);
  43362. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  43363. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  43364. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  43365. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  43366. }
  43367. this._buffer.update(this._vertexData);
  43368. // Render
  43369. var effect = this._effectBase;
  43370. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  43371. effect = this._effectFog;
  43372. }
  43373. engine.enableEffect(effect);
  43374. var viewMatrix = this._scene.getViewMatrix();
  43375. effect.setTexture("diffuseSampler", this._spriteTexture);
  43376. effect.setMatrix("view", viewMatrix);
  43377. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  43378. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  43379. // Fog
  43380. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  43381. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  43382. effect.setColor3("vFogColor", this._scene.fogColor);
  43383. }
  43384. // VBOs
  43385. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  43386. // Draw order
  43387. engine.setDepthFunctionToLessOrEqual();
  43388. effect.setBool("alphaTest", true);
  43389. engine.setColorWrite(false);
  43390. engine.draw(true, 0, max * 6);
  43391. engine.setColorWrite(true);
  43392. effect.setBool("alphaTest", false);
  43393. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  43394. engine.draw(true, 0, max * 6);
  43395. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  43396. };
  43397. SpriteManager.prototype.dispose = function () {
  43398. if (this._buffer) {
  43399. this._buffer.dispose();
  43400. this._buffer = null;
  43401. }
  43402. if (this._indexBuffer) {
  43403. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  43404. this._indexBuffer = null;
  43405. }
  43406. if (this._spriteTexture) {
  43407. this._spriteTexture.dispose();
  43408. this._spriteTexture = null;
  43409. }
  43410. // Remove from scene
  43411. var index = this._scene.spriteManagers.indexOf(this);
  43412. this._scene.spriteManagers.splice(index, 1);
  43413. // Callback
  43414. this.onDisposeObservable.notifyObservers(this);
  43415. this.onDisposeObservable.clear();
  43416. };
  43417. return SpriteManager;
  43418. }());
  43419. BABYLON.SpriteManager = SpriteManager;
  43420. })(BABYLON || (BABYLON = {}));
  43421. //# sourceMappingURL=babylon.spriteManager.js.map
  43422. var BABYLON;
  43423. (function (BABYLON) {
  43424. var Sprite = /** @class */ (function () {
  43425. function Sprite(name, manager) {
  43426. this.name = name;
  43427. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  43428. this.width = 1.0;
  43429. this.height = 1.0;
  43430. this.angle = 0;
  43431. this.cellIndex = 0;
  43432. this.invertU = 0;
  43433. this.invertV = 0;
  43434. this.animations = new Array();
  43435. this.isPickable = false;
  43436. this._animationStarted = false;
  43437. this._loopAnimation = false;
  43438. this._fromIndex = 0;
  43439. this._toIndex = 0;
  43440. this._delay = 0;
  43441. this._direction = 1;
  43442. this._time = 0;
  43443. this._manager = manager;
  43444. this._manager.sprites.push(this);
  43445. this.position = BABYLON.Vector3.Zero();
  43446. }
  43447. Object.defineProperty(Sprite.prototype, "size", {
  43448. get: function () {
  43449. return this.width;
  43450. },
  43451. set: function (value) {
  43452. this.width = value;
  43453. this.height = value;
  43454. },
  43455. enumerable: true,
  43456. configurable: true
  43457. });
  43458. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  43459. this._fromIndex = from;
  43460. this._toIndex = to;
  43461. this._loopAnimation = loop;
  43462. this._delay = delay;
  43463. this._animationStarted = true;
  43464. this._direction = from < to ? 1 : -1;
  43465. this.cellIndex = from;
  43466. this._time = 0;
  43467. this._onAnimationEnd = onAnimationEnd;
  43468. };
  43469. Sprite.prototype.stopAnimation = function () {
  43470. this._animationStarted = false;
  43471. };
  43472. Sprite.prototype._animate = function (deltaTime) {
  43473. if (!this._animationStarted)
  43474. return;
  43475. this._time += deltaTime;
  43476. if (this._time > this._delay) {
  43477. this._time = this._time % this._delay;
  43478. this.cellIndex += this._direction;
  43479. if (this.cellIndex > this._toIndex) {
  43480. if (this._loopAnimation) {
  43481. this.cellIndex = this._fromIndex;
  43482. }
  43483. else {
  43484. this.cellIndex = this._toIndex;
  43485. this._animationStarted = false;
  43486. if (this._onAnimationEnd) {
  43487. this._onAnimationEnd();
  43488. }
  43489. if (this.disposeWhenFinishedAnimating) {
  43490. this.dispose();
  43491. }
  43492. }
  43493. }
  43494. }
  43495. };
  43496. Sprite.prototype.dispose = function () {
  43497. for (var i = 0; i < this._manager.sprites.length; i++) {
  43498. if (this._manager.sprites[i] == this) {
  43499. this._manager.sprites.splice(i, 1);
  43500. }
  43501. }
  43502. };
  43503. return Sprite;
  43504. }());
  43505. BABYLON.Sprite = Sprite;
  43506. })(BABYLON || (BABYLON = {}));
  43507. //# sourceMappingURL=babylon.sprite.js.map
  43508. var BABYLON;
  43509. (function (BABYLON) {
  43510. var IntersectionInfo = /** @class */ (function () {
  43511. function IntersectionInfo(bu, bv, distance) {
  43512. this.bu = bu;
  43513. this.bv = bv;
  43514. this.distance = distance;
  43515. this.faceId = 0;
  43516. this.subMeshId = 0;
  43517. }
  43518. return IntersectionInfo;
  43519. }());
  43520. BABYLON.IntersectionInfo = IntersectionInfo;
  43521. var PickingInfo = /** @class */ (function () {
  43522. function PickingInfo() {
  43523. this.hit = false;
  43524. this.distance = 0;
  43525. this.pickedPoint = null;
  43526. this.pickedMesh = null;
  43527. this.bu = 0;
  43528. this.bv = 0;
  43529. this.faceId = -1;
  43530. this.subMeshId = 0;
  43531. this.pickedSprite = null;
  43532. }
  43533. // Methods
  43534. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  43535. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  43536. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  43537. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43538. return null;
  43539. }
  43540. var indices = this.pickedMesh.getIndices();
  43541. if (!indices) {
  43542. return null;
  43543. }
  43544. var result;
  43545. if (useVerticesNormals) {
  43546. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  43547. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  43548. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  43549. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  43550. normal0 = normal0.scale(this.bu);
  43551. normal1 = normal1.scale(this.bv);
  43552. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  43553. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  43554. }
  43555. else {
  43556. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43557. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  43558. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  43559. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  43560. var p1p2 = vertex1.subtract(vertex2);
  43561. var p3p2 = vertex3.subtract(vertex2);
  43562. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  43563. }
  43564. if (useWorldCoordinates) {
  43565. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  43566. }
  43567. return BABYLON.Vector3.Normalize(result);
  43568. };
  43569. PickingInfo.prototype.getTextureCoordinates = function () {
  43570. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  43571. return null;
  43572. }
  43573. var indices = this.pickedMesh.getIndices();
  43574. if (!indices) {
  43575. return null;
  43576. }
  43577. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  43578. if (!uvs) {
  43579. return null;
  43580. }
  43581. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  43582. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  43583. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  43584. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  43585. uv1 = uv1.scale(this.bu);
  43586. uv2 = uv2.scale(this.bv);
  43587. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  43588. };
  43589. return PickingInfo;
  43590. }());
  43591. BABYLON.PickingInfo = PickingInfo;
  43592. })(BABYLON || (BABYLON = {}));
  43593. //# sourceMappingURL=babylon.pickingInfo.js.map
  43594. var BABYLON;
  43595. (function (BABYLON) {
  43596. var Ray = /** @class */ (function () {
  43597. function Ray(origin, direction, length) {
  43598. if (length === void 0) { length = Number.MAX_VALUE; }
  43599. this.origin = origin;
  43600. this.direction = direction;
  43601. this.length = length;
  43602. }
  43603. // Methods
  43604. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  43605. var d = 0.0;
  43606. var maxValue = Number.MAX_VALUE;
  43607. var inv;
  43608. var min;
  43609. var max;
  43610. var temp;
  43611. if (Math.abs(this.direction.x) < 0.0000001) {
  43612. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  43613. return false;
  43614. }
  43615. }
  43616. else {
  43617. inv = 1.0 / this.direction.x;
  43618. min = (minimum.x - this.origin.x) * inv;
  43619. max = (maximum.x - this.origin.x) * inv;
  43620. if (max === -Infinity) {
  43621. max = Infinity;
  43622. }
  43623. if (min > max) {
  43624. temp = min;
  43625. min = max;
  43626. max = temp;
  43627. }
  43628. d = Math.max(min, d);
  43629. maxValue = Math.min(max, maxValue);
  43630. if (d > maxValue) {
  43631. return false;
  43632. }
  43633. }
  43634. if (Math.abs(this.direction.y) < 0.0000001) {
  43635. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  43636. return false;
  43637. }
  43638. }
  43639. else {
  43640. inv = 1.0 / this.direction.y;
  43641. min = (minimum.y - this.origin.y) * inv;
  43642. max = (maximum.y - this.origin.y) * inv;
  43643. if (max === -Infinity) {
  43644. max = Infinity;
  43645. }
  43646. if (min > max) {
  43647. temp = min;
  43648. min = max;
  43649. max = temp;
  43650. }
  43651. d = Math.max(min, d);
  43652. maxValue = Math.min(max, maxValue);
  43653. if (d > maxValue) {
  43654. return false;
  43655. }
  43656. }
  43657. if (Math.abs(this.direction.z) < 0.0000001) {
  43658. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  43659. return false;
  43660. }
  43661. }
  43662. else {
  43663. inv = 1.0 / this.direction.z;
  43664. min = (minimum.z - this.origin.z) * inv;
  43665. max = (maximum.z - this.origin.z) * inv;
  43666. if (max === -Infinity) {
  43667. max = Infinity;
  43668. }
  43669. if (min > max) {
  43670. temp = min;
  43671. min = max;
  43672. max = temp;
  43673. }
  43674. d = Math.max(min, d);
  43675. maxValue = Math.min(max, maxValue);
  43676. if (d > maxValue) {
  43677. return false;
  43678. }
  43679. }
  43680. return true;
  43681. };
  43682. Ray.prototype.intersectsBox = function (box) {
  43683. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  43684. };
  43685. Ray.prototype.intersectsSphere = function (sphere) {
  43686. var x = sphere.center.x - this.origin.x;
  43687. var y = sphere.center.y - this.origin.y;
  43688. var z = sphere.center.z - this.origin.z;
  43689. var pyth = (x * x) + (y * y) + (z * z);
  43690. var rr = sphere.radius * sphere.radius;
  43691. if (pyth <= rr) {
  43692. return true;
  43693. }
  43694. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  43695. if (dot < 0.0) {
  43696. return false;
  43697. }
  43698. var temp = pyth - (dot * dot);
  43699. return temp <= rr;
  43700. };
  43701. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  43702. if (!this._edge1) {
  43703. this._edge1 = BABYLON.Vector3.Zero();
  43704. this._edge2 = BABYLON.Vector3.Zero();
  43705. this._pvec = BABYLON.Vector3.Zero();
  43706. this._tvec = BABYLON.Vector3.Zero();
  43707. this._qvec = BABYLON.Vector3.Zero();
  43708. }
  43709. vertex1.subtractToRef(vertex0, this._edge1);
  43710. vertex2.subtractToRef(vertex0, this._edge2);
  43711. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  43712. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  43713. if (det === 0) {
  43714. return null;
  43715. }
  43716. var invdet = 1 / det;
  43717. this.origin.subtractToRef(vertex0, this._tvec);
  43718. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  43719. if (bu < 0 || bu > 1.0) {
  43720. return null;
  43721. }
  43722. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  43723. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  43724. if (bv < 0 || bu + bv > 1.0) {
  43725. return null;
  43726. }
  43727. //check if the distance is longer than the predefined length.
  43728. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  43729. if (distance > this.length) {
  43730. return null;
  43731. }
  43732. return new BABYLON.IntersectionInfo(bu, bv, distance);
  43733. };
  43734. Ray.prototype.intersectsPlane = function (plane) {
  43735. var distance;
  43736. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  43737. if (Math.abs(result1) < 9.99999997475243E-07) {
  43738. return null;
  43739. }
  43740. else {
  43741. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  43742. distance = (-plane.d - result2) / result1;
  43743. if (distance < 0.0) {
  43744. if (distance < -9.99999997475243E-07) {
  43745. return null;
  43746. }
  43747. else {
  43748. return 0;
  43749. }
  43750. }
  43751. return distance;
  43752. }
  43753. };
  43754. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  43755. var tm = BABYLON.Tmp.Matrix[0];
  43756. mesh.getWorldMatrix().invertToRef(tm);
  43757. if (this._tmpRay) {
  43758. Ray.TransformToRef(this, tm, this._tmpRay);
  43759. }
  43760. else {
  43761. this._tmpRay = Ray.Transform(this, tm);
  43762. }
  43763. return mesh.intersects(this._tmpRay, fastCheck);
  43764. };
  43765. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  43766. if (results) {
  43767. results.length = 0;
  43768. }
  43769. else {
  43770. results = [];
  43771. }
  43772. for (var i = 0; i < meshes.length; i++) {
  43773. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  43774. if (pickInfo.hit) {
  43775. results.push(pickInfo);
  43776. }
  43777. }
  43778. results.sort(this._comparePickingInfo);
  43779. return results;
  43780. };
  43781. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  43782. if (pickingInfoA.distance < pickingInfoB.distance) {
  43783. return -1;
  43784. }
  43785. else if (pickingInfoA.distance > pickingInfoB.distance) {
  43786. return 1;
  43787. }
  43788. else {
  43789. return 0;
  43790. }
  43791. };
  43792. /**
  43793. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  43794. * @param sega the first point of the segment to test the intersection against
  43795. * @param segb the second point of the segment to test the intersection against
  43796. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  43797. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  43798. */
  43799. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  43800. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  43801. var u = segb.subtract(sega);
  43802. var v = rsegb.subtract(this.origin);
  43803. var w = sega.subtract(this.origin);
  43804. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  43805. var b = BABYLON.Vector3.Dot(u, v);
  43806. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  43807. var d = BABYLON.Vector3.Dot(u, w);
  43808. var e = BABYLON.Vector3.Dot(v, w);
  43809. var D = a * c - b * b; // always >= 0
  43810. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  43811. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  43812. // compute the line parameters of the two closest points
  43813. if (D < Ray.smallnum) {
  43814. sN = 0.0; // force using point P0 on segment S1
  43815. sD = 1.0; // to prevent possible division by 0.0 later
  43816. tN = e;
  43817. tD = c;
  43818. }
  43819. else {
  43820. sN = (b * e - c * d);
  43821. tN = (a * e - b * d);
  43822. if (sN < 0.0) {
  43823. sN = 0.0;
  43824. tN = e;
  43825. tD = c;
  43826. }
  43827. else if (sN > sD) {
  43828. sN = sD;
  43829. tN = e + b;
  43830. tD = c;
  43831. }
  43832. }
  43833. if (tN < 0.0) {
  43834. tN = 0.0;
  43835. // recompute sc for this edge
  43836. if (-d < 0.0) {
  43837. sN = 0.0;
  43838. }
  43839. else if (-d > a)
  43840. sN = sD;
  43841. else {
  43842. sN = -d;
  43843. sD = a;
  43844. }
  43845. }
  43846. else if (tN > tD) {
  43847. tN = tD;
  43848. // recompute sc for this edge
  43849. if ((-d + b) < 0.0) {
  43850. sN = 0;
  43851. }
  43852. else if ((-d + b) > a) {
  43853. sN = sD;
  43854. }
  43855. else {
  43856. sN = (-d + b);
  43857. sD = a;
  43858. }
  43859. }
  43860. // finally do the division to get sc and tc
  43861. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  43862. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  43863. // get the difference of the two closest points
  43864. var qtc = v.multiplyByFloats(tc, tc, tc);
  43865. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  43866. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  43867. if (isIntersected) {
  43868. return qtc.length();
  43869. }
  43870. return -1;
  43871. };
  43872. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  43873. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  43874. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  43875. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  43876. this.direction.normalize();
  43877. return this;
  43878. };
  43879. // Statics
  43880. Ray.Zero = function () {
  43881. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  43882. };
  43883. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  43884. var result = Ray.Zero();
  43885. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  43886. };
  43887. /**
  43888. * 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
  43889. * transformed to the given world matrix.
  43890. * @param origin The origin point
  43891. * @param end The end point
  43892. * @param world a matrix to transform the ray to. Default is the identity matrix.
  43893. */
  43894. Ray.CreateNewFromTo = function (origin, end, world) {
  43895. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  43896. var direction = end.subtract(origin);
  43897. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  43898. direction.normalize();
  43899. return Ray.Transform(new Ray(origin, direction, length), world);
  43900. };
  43901. Ray.Transform = function (ray, matrix) {
  43902. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  43903. Ray.TransformToRef(ray, matrix, result);
  43904. return result;
  43905. };
  43906. Ray.TransformToRef = function (ray, matrix, result) {
  43907. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  43908. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  43909. result.length = ray.length;
  43910. var dir = result.direction;
  43911. var len = dir.length();
  43912. if (!(len === 0 || len === 1)) {
  43913. var num = 1.0 / len;
  43914. dir.x *= num;
  43915. dir.y *= num;
  43916. dir.z *= num;
  43917. result.length *= len;
  43918. }
  43919. };
  43920. Ray.smallnum = 0.00000001;
  43921. Ray.rayl = 10e8;
  43922. return Ray;
  43923. }());
  43924. BABYLON.Ray = Ray;
  43925. })(BABYLON || (BABYLON = {}));
  43926. //# sourceMappingURL=babylon.ray.js.map
  43927. var BABYLON;
  43928. (function (BABYLON) {
  43929. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  43930. if (boxMin.x > sphereCenter.x + sphereRadius)
  43931. return false;
  43932. if (sphereCenter.x - sphereRadius > boxMax.x)
  43933. return false;
  43934. if (boxMin.y > sphereCenter.y + sphereRadius)
  43935. return false;
  43936. if (sphereCenter.y - sphereRadius > boxMax.y)
  43937. return false;
  43938. if (boxMin.z > sphereCenter.z + sphereRadius)
  43939. return false;
  43940. if (sphereCenter.z - sphereRadius > boxMax.z)
  43941. return false;
  43942. return true;
  43943. };
  43944. var getLowestRoot = (function () {
  43945. var result = { root: 0, found: false };
  43946. return function (a, b, c, maxR) {
  43947. result.root = 0;
  43948. result.found = false;
  43949. var determinant = b * b - 4.0 * a * c;
  43950. if (determinant < 0)
  43951. return result;
  43952. var sqrtD = Math.sqrt(determinant);
  43953. var r1 = (-b - sqrtD) / (2.0 * a);
  43954. var r2 = (-b + sqrtD) / (2.0 * a);
  43955. if (r1 > r2) {
  43956. var temp = r2;
  43957. r2 = r1;
  43958. r1 = temp;
  43959. }
  43960. if (r1 > 0 && r1 < maxR) {
  43961. result.root = r1;
  43962. result.found = true;
  43963. return result;
  43964. }
  43965. if (r2 > 0 && r2 < maxR) {
  43966. result.root = r2;
  43967. result.found = true;
  43968. return result;
  43969. }
  43970. return result;
  43971. };
  43972. })();
  43973. var Collider = /** @class */ (function () {
  43974. function Collider() {
  43975. this.radius = BABYLON.Vector3.One();
  43976. this.retry = 0;
  43977. this.basePointWorld = BABYLON.Vector3.Zero();
  43978. this.velocityWorld = BABYLON.Vector3.Zero();
  43979. this.normalizedVelocity = BABYLON.Vector3.Zero();
  43980. this._collisionPoint = BABYLON.Vector3.Zero();
  43981. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  43982. this._tempVector = BABYLON.Vector3.Zero();
  43983. this._tempVector2 = BABYLON.Vector3.Zero();
  43984. this._tempVector3 = BABYLON.Vector3.Zero();
  43985. this._tempVector4 = BABYLON.Vector3.Zero();
  43986. this._edge = BABYLON.Vector3.Zero();
  43987. this._baseToVertex = BABYLON.Vector3.Zero();
  43988. this._destinationPoint = BABYLON.Vector3.Zero();
  43989. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  43990. this._displacementVector = BABYLON.Vector3.Zero();
  43991. this._collisionMask = -1;
  43992. }
  43993. Object.defineProperty(Collider.prototype, "collisionMask", {
  43994. get: function () {
  43995. return this._collisionMask;
  43996. },
  43997. set: function (mask) {
  43998. this._collisionMask = !isNaN(mask) ? mask : -1;
  43999. },
  44000. enumerable: true,
  44001. configurable: true
  44002. });
  44003. // Methods
  44004. Collider.prototype._initialize = function (source, dir, e) {
  44005. this.velocity = dir;
  44006. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  44007. this.basePoint = source;
  44008. source.multiplyToRef(this.radius, this.basePointWorld);
  44009. dir.multiplyToRef(this.radius, this.velocityWorld);
  44010. this.velocityWorldLength = this.velocityWorld.length();
  44011. this.epsilon = e;
  44012. this.collisionFound = false;
  44013. };
  44014. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  44015. pa.subtractToRef(point, this._tempVector);
  44016. pb.subtractToRef(point, this._tempVector2);
  44017. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  44018. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  44019. if (d < 0)
  44020. return false;
  44021. pc.subtractToRef(point, this._tempVector3);
  44022. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  44023. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  44024. if (d < 0)
  44025. return false;
  44026. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  44027. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  44028. return d >= 0;
  44029. };
  44030. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  44031. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  44032. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  44033. if (distance > this.velocityWorldLength + max + sphereRadius) {
  44034. return false;
  44035. }
  44036. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  44037. return false;
  44038. return true;
  44039. };
  44040. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  44041. var t0;
  44042. var embeddedInPlane = false;
  44043. //defensive programming, actually not needed.
  44044. if (!trianglePlaneArray) {
  44045. trianglePlaneArray = [];
  44046. }
  44047. if (!trianglePlaneArray[faceIndex]) {
  44048. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  44049. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  44050. }
  44051. var trianglePlane = trianglePlaneArray[faceIndex];
  44052. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  44053. return;
  44054. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  44055. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  44056. if (normalDotVelocity == 0) {
  44057. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  44058. return;
  44059. embeddedInPlane = true;
  44060. t0 = 0;
  44061. }
  44062. else {
  44063. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  44064. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  44065. if (t0 > t1) {
  44066. var temp = t1;
  44067. t1 = t0;
  44068. t0 = temp;
  44069. }
  44070. if (t0 > 1.0 || t1 < 0.0)
  44071. return;
  44072. if (t0 < 0)
  44073. t0 = 0;
  44074. if (t0 > 1.0)
  44075. t0 = 1.0;
  44076. }
  44077. this._collisionPoint.copyFromFloats(0, 0, 0);
  44078. var found = false;
  44079. var t = 1.0;
  44080. if (!embeddedInPlane) {
  44081. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  44082. this.velocity.scaleToRef(t0, this._tempVector);
  44083. this._planeIntersectionPoint.addInPlace(this._tempVector);
  44084. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  44085. found = true;
  44086. t = t0;
  44087. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  44088. }
  44089. }
  44090. if (!found) {
  44091. var velocitySquaredLength = this.velocity.lengthSquared();
  44092. var a = velocitySquaredLength;
  44093. this.basePoint.subtractToRef(p1, this._tempVector);
  44094. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  44095. var c = this._tempVector.lengthSquared() - 1.0;
  44096. var lowestRoot = getLowestRoot(a, b, c, t);
  44097. if (lowestRoot.found) {
  44098. t = lowestRoot.root;
  44099. found = true;
  44100. this._collisionPoint.copyFrom(p1);
  44101. }
  44102. this.basePoint.subtractToRef(p2, this._tempVector);
  44103. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  44104. c = this._tempVector.lengthSquared() - 1.0;
  44105. lowestRoot = getLowestRoot(a, b, c, t);
  44106. if (lowestRoot.found) {
  44107. t = lowestRoot.root;
  44108. found = true;
  44109. this._collisionPoint.copyFrom(p2);
  44110. }
  44111. this.basePoint.subtractToRef(p3, this._tempVector);
  44112. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  44113. c = this._tempVector.lengthSquared() - 1.0;
  44114. lowestRoot = getLowestRoot(a, b, c, t);
  44115. if (lowestRoot.found) {
  44116. t = lowestRoot.root;
  44117. found = true;
  44118. this._collisionPoint.copyFrom(p3);
  44119. }
  44120. p2.subtractToRef(p1, this._edge);
  44121. p1.subtractToRef(this.basePoint, this._baseToVertex);
  44122. var edgeSquaredLength = this._edge.lengthSquared();
  44123. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  44124. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  44125. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  44126. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  44127. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  44128. lowestRoot = getLowestRoot(a, b, c, t);
  44129. if (lowestRoot.found) {
  44130. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  44131. if (f >= 0.0 && f <= 1.0) {
  44132. t = lowestRoot.root;
  44133. found = true;
  44134. this._edge.scaleInPlace(f);
  44135. p1.addToRef(this._edge, this._collisionPoint);
  44136. }
  44137. }
  44138. p3.subtractToRef(p2, this._edge);
  44139. p2.subtractToRef(this.basePoint, this._baseToVertex);
  44140. edgeSquaredLength = this._edge.lengthSquared();
  44141. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  44142. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  44143. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  44144. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  44145. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  44146. lowestRoot = getLowestRoot(a, b, c, t);
  44147. if (lowestRoot.found) {
  44148. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  44149. if (f >= 0.0 && f <= 1.0) {
  44150. t = lowestRoot.root;
  44151. found = true;
  44152. this._edge.scaleInPlace(f);
  44153. p2.addToRef(this._edge, this._collisionPoint);
  44154. }
  44155. }
  44156. p1.subtractToRef(p3, this._edge);
  44157. p3.subtractToRef(this.basePoint, this._baseToVertex);
  44158. edgeSquaredLength = this._edge.lengthSquared();
  44159. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  44160. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  44161. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  44162. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  44163. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  44164. lowestRoot = getLowestRoot(a, b, c, t);
  44165. if (lowestRoot.found) {
  44166. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  44167. if (f >= 0.0 && f <= 1.0) {
  44168. t = lowestRoot.root;
  44169. found = true;
  44170. this._edge.scaleInPlace(f);
  44171. p3.addToRef(this._edge, this._collisionPoint);
  44172. }
  44173. }
  44174. }
  44175. if (found) {
  44176. var distToCollision = t * this.velocity.length();
  44177. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  44178. if (!this.intersectionPoint) {
  44179. this.intersectionPoint = this._collisionPoint.clone();
  44180. }
  44181. else {
  44182. this.intersectionPoint.copyFrom(this._collisionPoint);
  44183. }
  44184. this.nearestDistance = distToCollision;
  44185. this.collisionFound = true;
  44186. }
  44187. }
  44188. };
  44189. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  44190. for (var i = indexStart; i < indexEnd; i += 3) {
  44191. var p1 = pts[indices[i] - decal];
  44192. var p2 = pts[indices[i + 1] - decal];
  44193. var p3 = pts[indices[i + 2] - decal];
  44194. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  44195. }
  44196. };
  44197. Collider.prototype._getResponse = function (pos, vel) {
  44198. pos.addToRef(vel, this._destinationPoint);
  44199. vel.scaleInPlace((this.nearestDistance / vel.length()));
  44200. this.basePoint.addToRef(vel, pos);
  44201. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  44202. this._slidePlaneNormal.normalize();
  44203. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  44204. pos.addInPlace(this._displacementVector);
  44205. this.intersectionPoint.addInPlace(this._displacementVector);
  44206. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  44207. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  44208. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  44209. };
  44210. return Collider;
  44211. }());
  44212. BABYLON.Collider = Collider;
  44213. })(BABYLON || (BABYLON = {}));
  44214. //# sourceMappingURL=babylon.collider.js.map
  44215. var BABYLON;
  44216. (function (BABYLON) {
  44217. //WebWorker code will be inserted to this variable.
  44218. BABYLON.CollisionWorker = "";
  44219. var WorkerTaskType;
  44220. (function (WorkerTaskType) {
  44221. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  44222. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  44223. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  44224. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  44225. var WorkerReplyType;
  44226. (function (WorkerReplyType) {
  44227. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  44228. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  44229. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  44230. var CollisionCoordinatorWorker = /** @class */ (function () {
  44231. function CollisionCoordinatorWorker() {
  44232. var _this = this;
  44233. this._scaledPosition = BABYLON.Vector3.Zero();
  44234. this._scaledVelocity = BABYLON.Vector3.Zero();
  44235. this.onMeshUpdated = function (mesh) {
  44236. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  44237. };
  44238. this.onGeometryUpdated = function (geometry) {
  44239. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  44240. };
  44241. this._afterRender = function () {
  44242. if (!_this._init)
  44243. return;
  44244. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  44245. return;
  44246. }
  44247. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  44248. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  44249. if (_this._runningUpdated > 4) {
  44250. return;
  44251. }
  44252. ++_this._runningUpdated;
  44253. var payload = {
  44254. updatedMeshes: _this._addUpdateMeshesList,
  44255. updatedGeometries: _this._addUpdateGeometriesList,
  44256. removedGeometries: _this._toRemoveGeometryArray,
  44257. removedMeshes: _this._toRemoveMeshesArray
  44258. };
  44259. var message = {
  44260. payload: payload,
  44261. taskType: WorkerTaskType.UPDATE
  44262. };
  44263. var serializable = [];
  44264. for (var id in payload.updatedGeometries) {
  44265. if (payload.updatedGeometries.hasOwnProperty(id)) {
  44266. //prepare transferables
  44267. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  44268. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  44269. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  44270. }
  44271. }
  44272. _this._worker.postMessage(message, serializable);
  44273. _this._addUpdateMeshesList = {};
  44274. _this._addUpdateGeometriesList = {};
  44275. _this._toRemoveGeometryArray = [];
  44276. _this._toRemoveMeshesArray = [];
  44277. };
  44278. this._onMessageFromWorker = function (e) {
  44279. var returnData = e.data;
  44280. if (returnData.error != WorkerReplyType.SUCCESS) {
  44281. //TODO what errors can be returned from the worker?
  44282. BABYLON.Tools.Warn("error returned from worker!");
  44283. return;
  44284. }
  44285. switch (returnData.taskType) {
  44286. case WorkerTaskType.INIT:
  44287. _this._init = true;
  44288. //Update the worked with ALL of the scene's current state
  44289. _this._scene.meshes.forEach(function (mesh) {
  44290. _this.onMeshAdded(mesh);
  44291. });
  44292. _this._scene.getGeometries().forEach(function (geometry) {
  44293. _this.onGeometryAdded(geometry);
  44294. });
  44295. break;
  44296. case WorkerTaskType.UPDATE:
  44297. _this._runningUpdated--;
  44298. break;
  44299. case WorkerTaskType.COLLIDE:
  44300. var returnPayload = returnData.payload;
  44301. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  44302. return;
  44303. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  44304. if (callback) {
  44305. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  44306. if (mesh) {
  44307. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  44308. }
  44309. }
  44310. //cleanup
  44311. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  44312. break;
  44313. }
  44314. };
  44315. this._collisionsCallbackArray = [];
  44316. this._init = false;
  44317. this._runningUpdated = 0;
  44318. this._addUpdateMeshesList = {};
  44319. this._addUpdateGeometriesList = {};
  44320. this._toRemoveGeometryArray = [];
  44321. this._toRemoveMeshesArray = [];
  44322. }
  44323. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  44324. if (!this._init)
  44325. return;
  44326. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  44327. return;
  44328. position.divideToRef(collider.radius, this._scaledPosition);
  44329. displacement.divideToRef(collider.radius, this._scaledVelocity);
  44330. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  44331. var payload = {
  44332. collider: {
  44333. position: this._scaledPosition.asArray(),
  44334. velocity: this._scaledVelocity.asArray(),
  44335. radius: collider.radius.asArray()
  44336. },
  44337. collisionId: collisionIndex,
  44338. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  44339. maximumRetry: maximumRetry
  44340. };
  44341. var message = {
  44342. payload: payload,
  44343. taskType: WorkerTaskType.COLLIDE
  44344. };
  44345. this._worker.postMessage(message);
  44346. };
  44347. CollisionCoordinatorWorker.prototype.init = function (scene) {
  44348. this._scene = scene;
  44349. this._scene.registerAfterRender(this._afterRender);
  44350. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  44351. this._worker = new Worker(workerUrl);
  44352. this._worker.onmessage = this._onMessageFromWorker;
  44353. var message = {
  44354. payload: {},
  44355. taskType: WorkerTaskType.INIT
  44356. };
  44357. this._worker.postMessage(message);
  44358. };
  44359. CollisionCoordinatorWorker.prototype.destroy = function () {
  44360. this._scene.unregisterAfterRender(this._afterRender);
  44361. this._worker.terminate();
  44362. };
  44363. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  44364. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  44365. this.onMeshUpdated(mesh);
  44366. };
  44367. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  44368. this._toRemoveMeshesArray.push(mesh.uniqueId);
  44369. };
  44370. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  44371. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  44372. geometry.onGeometryUpdated = this.onGeometryUpdated;
  44373. this.onGeometryUpdated(geometry);
  44374. };
  44375. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  44376. this._toRemoveGeometryArray.push(geometry.id);
  44377. };
  44378. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  44379. var submeshes = [];
  44380. if (mesh.subMeshes) {
  44381. submeshes = mesh.subMeshes.map(function (sm, idx) {
  44382. var boundingInfo = sm.getBoundingInfo();
  44383. return {
  44384. position: idx,
  44385. verticesStart: sm.verticesStart,
  44386. verticesCount: sm.verticesCount,
  44387. indexStart: sm.indexStart,
  44388. indexCount: sm.indexCount,
  44389. hasMaterial: !!sm.getMaterial(),
  44390. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  44391. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  44392. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  44393. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  44394. };
  44395. });
  44396. }
  44397. var geometryId = null;
  44398. if (mesh instanceof BABYLON.Mesh) {
  44399. var geometry = mesh.geometry;
  44400. geometryId = geometry ? geometry.id : null;
  44401. }
  44402. else if (mesh instanceof BABYLON.InstancedMesh) {
  44403. var geometry = mesh.sourceMesh.geometry;
  44404. geometryId = geometry ? geometry.id : null;
  44405. }
  44406. var boundingInfo = mesh.getBoundingInfo();
  44407. return {
  44408. uniqueId: mesh.uniqueId,
  44409. id: mesh.id,
  44410. name: mesh.name,
  44411. geometryId: geometryId,
  44412. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  44413. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  44414. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  44415. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  44416. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  44417. subMeshes: submeshes,
  44418. checkCollisions: mesh.checkCollisions
  44419. };
  44420. };
  44421. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  44422. return {
  44423. id: geometry.id,
  44424. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  44425. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  44426. indices: new Uint32Array(geometry.getIndices() || []),
  44427. };
  44428. };
  44429. return CollisionCoordinatorWorker;
  44430. }());
  44431. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  44432. var CollisionCoordinatorLegacy = /** @class */ (function () {
  44433. function CollisionCoordinatorLegacy() {
  44434. this._scaledPosition = BABYLON.Vector3.Zero();
  44435. this._scaledVelocity = BABYLON.Vector3.Zero();
  44436. this._finalPosition = BABYLON.Vector3.Zero();
  44437. }
  44438. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  44439. position.divideToRef(collider.radius, this._scaledPosition);
  44440. displacement.divideToRef(collider.radius, this._scaledVelocity);
  44441. collider.collidedMesh = null;
  44442. collider.retry = 0;
  44443. collider.initialVelocity = this._scaledVelocity;
  44444. collider.initialPosition = this._scaledPosition;
  44445. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  44446. this._finalPosition.multiplyInPlace(collider.radius);
  44447. //run the callback
  44448. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  44449. };
  44450. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  44451. this._scene = scene;
  44452. };
  44453. CollisionCoordinatorLegacy.prototype.destroy = function () {
  44454. //Legacy need no destruction method.
  44455. };
  44456. //No update in legacy mode
  44457. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  44458. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  44459. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  44460. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  44461. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  44462. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  44463. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  44464. if (excludedMesh === void 0) { excludedMesh = null; }
  44465. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  44466. if (collider.retry >= maximumRetry) {
  44467. finalPosition.copyFrom(position);
  44468. return;
  44469. }
  44470. // Check if this is a mesh else camera or -1
  44471. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  44472. collider._initialize(position, velocity, closeDistance);
  44473. // Check all meshes
  44474. for (var index = 0; index < this._scene.meshes.length; index++) {
  44475. var mesh = this._scene.meshes[index];
  44476. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  44477. mesh._checkCollision(collider);
  44478. }
  44479. }
  44480. if (!collider.collisionFound) {
  44481. position.addToRef(velocity, finalPosition);
  44482. return;
  44483. }
  44484. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  44485. collider._getResponse(position, velocity);
  44486. }
  44487. if (velocity.length() <= closeDistance) {
  44488. finalPosition.copyFrom(position);
  44489. return;
  44490. }
  44491. collider.retry++;
  44492. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  44493. };
  44494. return CollisionCoordinatorLegacy;
  44495. }());
  44496. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  44497. })(BABYLON || (BABYLON = {}));
  44498. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  44499. var BABYLON;
  44500. (function (BABYLON) {
  44501. var Particle = /** @class */ (function () {
  44502. function Particle(particleSystem) {
  44503. this.particleSystem = particleSystem;
  44504. this.position = BABYLON.Vector3.Zero();
  44505. this.direction = BABYLON.Vector3.Zero();
  44506. this.color = new BABYLON.Color4(0, 0, 0, 0);
  44507. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  44508. this.lifeTime = 1.0;
  44509. this.age = 0;
  44510. this.size = 0;
  44511. this.angle = 0;
  44512. this.angularSpeed = 0;
  44513. this._currentFrameCounter = 0;
  44514. this.cellIndex = 0;
  44515. if (!this.particleSystem.isAnimationSheetEnabled) {
  44516. return;
  44517. }
  44518. this.cellIndex = this.particleSystem.startSpriteCellID;
  44519. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  44520. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  44521. }
  44522. else {
  44523. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  44524. }
  44525. }
  44526. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  44527. // (ageOffset / scaledUpdateSpeed) / available cells
  44528. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  44529. this._currentFrameCounter += scaledUpdateSpeed;
  44530. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  44531. this._currentFrameCounter = 0;
  44532. this.cellIndex++;
  44533. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  44534. this.cellIndex = this.particleSystem.endSpriteCellID;
  44535. }
  44536. }
  44537. };
  44538. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  44539. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  44540. this.cellIndex++;
  44541. this._currentFrameCounter = 0;
  44542. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  44543. if (this.particleSystem.spriteCellLoop) {
  44544. this.cellIndex = this.particleSystem.startSpriteCellID;
  44545. }
  44546. else {
  44547. this.cellIndex = this.particleSystem.endSpriteCellID;
  44548. }
  44549. }
  44550. }
  44551. else {
  44552. this._currentFrameCounter++;
  44553. }
  44554. };
  44555. Particle.prototype.copyTo = function (other) {
  44556. other.position.copyFrom(this.position);
  44557. other.direction.copyFrom(this.direction);
  44558. other.color.copyFrom(this.color);
  44559. other.colorStep.copyFrom(this.colorStep);
  44560. other.lifeTime = this.lifeTime;
  44561. other.age = this.age;
  44562. other.size = this.size;
  44563. other.angle = this.angle;
  44564. other.angularSpeed = this.angularSpeed;
  44565. other.particleSystem = this.particleSystem;
  44566. other.cellIndex = this.cellIndex;
  44567. };
  44568. return Particle;
  44569. }());
  44570. BABYLON.Particle = Particle;
  44571. })(BABYLON || (BABYLON = {}));
  44572. //# sourceMappingURL=babylon.particle.js.map
  44573. var BABYLON;
  44574. (function (BABYLON) {
  44575. var randomNumber = function (min, max) {
  44576. if (min === max) {
  44577. return (min);
  44578. }
  44579. var random = Math.random();
  44580. return ((random * (max - min)) + min);
  44581. };
  44582. var ParticleSystem = /** @class */ (function () {
  44583. // end of sheet animation
  44584. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  44585. if (customEffect === void 0) { customEffect = null; }
  44586. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  44587. if (epsilon === void 0) { epsilon = 0.01; }
  44588. var _this = this;
  44589. this.name = name;
  44590. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  44591. // Members
  44592. this.animations = [];
  44593. this.renderingGroupId = 0;
  44594. this.emitter = null;
  44595. this.emitRate = 10;
  44596. this.manualEmitCount = -1;
  44597. this.updateSpeed = 0.01;
  44598. this.targetStopDuration = 0;
  44599. this.disposeOnStop = false;
  44600. this.minEmitPower = 1;
  44601. this.maxEmitPower = 1;
  44602. this.minLifeTime = 1;
  44603. this.maxLifeTime = 1;
  44604. this.minSize = 1;
  44605. this.maxSize = 1;
  44606. this.minAngularSpeed = 0;
  44607. this.maxAngularSpeed = 0;
  44608. this.layerMask = 0x0FFFFFFF;
  44609. this.customShader = null;
  44610. this.preventAutoStart = false;
  44611. /**
  44612. * An event triggered when the system is disposed.
  44613. * @type {BABYLON.Observable}
  44614. */
  44615. this.onDisposeObservable = new BABYLON.Observable();
  44616. this.onAnimationEnd = null;
  44617. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  44618. this.forceDepthWrite = false;
  44619. this.gravity = BABYLON.Vector3.Zero();
  44620. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  44621. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  44622. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  44623. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44624. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44625. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44626. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  44627. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44628. this.particles = new Array();
  44629. this._stockParticles = new Array();
  44630. this._newPartsExcess = 0;
  44631. this._vertexBuffers = {};
  44632. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  44633. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  44634. this._scaledDirection = BABYLON.Vector3.Zero();
  44635. this._scaledGravity = BABYLON.Vector3.Zero();
  44636. this._currentRenderId = -1;
  44637. this._started = false;
  44638. this._stopped = false;
  44639. this._actualFrame = 0;
  44640. // sheet animation
  44641. this.startSpriteCellID = 0;
  44642. this.endSpriteCellID = 0;
  44643. this.spriteCellLoop = true;
  44644. this.spriteCellChangeSpeed = 0;
  44645. this.spriteCellWidth = 0;
  44646. this.spriteCellHeight = 0;
  44647. this._vertexBufferSize = 11;
  44648. this.appendParticleVertexes = null;
  44649. this.id = name;
  44650. this._capacity = capacity;
  44651. this._epsilon = epsilon;
  44652. if (_isAnimationSheetEnabled) {
  44653. this._vertexBufferSize = 12;
  44654. }
  44655. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44656. this._customEffect = customEffect;
  44657. scene.particleSystems.push(this);
  44658. this._createIndexBuffer();
  44659. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  44660. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  44661. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  44662. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  44663. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  44664. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  44665. if (this._isAnimationSheetEnabled) {
  44666. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  44667. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  44668. }
  44669. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  44670. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  44671. this._vertexBuffers["options"] = options;
  44672. // Default behaviors
  44673. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  44674. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  44675. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  44676. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  44677. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  44678. };
  44679. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  44680. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  44681. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  44682. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  44683. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  44684. };
  44685. this.updateFunction = function (particles) {
  44686. for (var index = 0; index < particles.length; index++) {
  44687. var particle = particles[index];
  44688. particle.age += _this._scaledUpdateSpeed;
  44689. if (particle.age >= particle.lifeTime) {
  44690. _this.recycleParticle(particle);
  44691. index--;
  44692. continue;
  44693. }
  44694. else {
  44695. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  44696. particle.color.addInPlace(_this._scaledColorStep);
  44697. if (particle.color.a < 0)
  44698. particle.color.a = 0;
  44699. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  44700. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  44701. particle.position.addInPlace(_this._scaledDirection);
  44702. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  44703. particle.direction.addInPlace(_this._scaledGravity);
  44704. if (_this._isAnimationSheetEnabled) {
  44705. particle.updateCellIndex(_this._scaledUpdateSpeed);
  44706. }
  44707. }
  44708. }
  44709. };
  44710. }
  44711. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  44712. set: function (callback) {
  44713. if (this._onDisposeObserver) {
  44714. this.onDisposeObservable.remove(this._onDisposeObserver);
  44715. }
  44716. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  44717. },
  44718. enumerable: true,
  44719. configurable: true
  44720. });
  44721. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  44722. get: function () {
  44723. return this._isAnimationSheetEnabled;
  44724. },
  44725. enumerable: true,
  44726. configurable: true
  44727. });
  44728. ParticleSystem.prototype._createIndexBuffer = function () {
  44729. var indices = [];
  44730. var index = 0;
  44731. for (var count = 0; count < this._capacity; count++) {
  44732. indices.push(index);
  44733. indices.push(index + 1);
  44734. indices.push(index + 2);
  44735. indices.push(index);
  44736. indices.push(index + 2);
  44737. indices.push(index + 3);
  44738. index += 4;
  44739. }
  44740. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  44741. };
  44742. ParticleSystem.prototype.recycleParticle = function (particle) {
  44743. var lastParticle = this.particles.pop();
  44744. if (lastParticle !== particle) {
  44745. lastParticle.copyTo(particle);
  44746. this._stockParticles.push(lastParticle);
  44747. }
  44748. };
  44749. ParticleSystem.prototype.getCapacity = function () {
  44750. return this._capacity;
  44751. };
  44752. ParticleSystem.prototype.isAlive = function () {
  44753. return this._alive;
  44754. };
  44755. ParticleSystem.prototype.isStarted = function () {
  44756. return this._started;
  44757. };
  44758. ParticleSystem.prototype.start = function () {
  44759. this._started = true;
  44760. this._stopped = false;
  44761. this._actualFrame = 0;
  44762. };
  44763. ParticleSystem.prototype.stop = function () {
  44764. this._stopped = true;
  44765. };
  44766. // animation sheet
  44767. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  44768. var offset = index * this._vertexBufferSize;
  44769. this._vertexData[offset] = particle.position.x;
  44770. this._vertexData[offset + 1] = particle.position.y;
  44771. this._vertexData[offset + 2] = particle.position.z;
  44772. this._vertexData[offset + 3] = particle.color.r;
  44773. this._vertexData[offset + 4] = particle.color.g;
  44774. this._vertexData[offset + 5] = particle.color.b;
  44775. this._vertexData[offset + 6] = particle.color.a;
  44776. this._vertexData[offset + 7] = particle.angle;
  44777. this._vertexData[offset + 8] = particle.size;
  44778. this._vertexData[offset + 9] = offsetX;
  44779. this._vertexData[offset + 10] = offsetY;
  44780. };
  44781. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  44782. if (offsetX === 0)
  44783. offsetX = this._epsilon;
  44784. else if (offsetX === 1)
  44785. offsetX = 1 - this._epsilon;
  44786. if (offsetY === 0)
  44787. offsetY = this._epsilon;
  44788. else if (offsetY === 1)
  44789. offsetY = 1 - this._epsilon;
  44790. var offset = index * this._vertexBufferSize;
  44791. this._vertexData[offset] = particle.position.x;
  44792. this._vertexData[offset + 1] = particle.position.y;
  44793. this._vertexData[offset + 2] = particle.position.z;
  44794. this._vertexData[offset + 3] = particle.color.r;
  44795. this._vertexData[offset + 4] = particle.color.g;
  44796. this._vertexData[offset + 5] = particle.color.b;
  44797. this._vertexData[offset + 6] = particle.color.a;
  44798. this._vertexData[offset + 7] = particle.angle;
  44799. this._vertexData[offset + 8] = particle.size;
  44800. this._vertexData[offset + 9] = offsetX;
  44801. this._vertexData[offset + 10] = offsetY;
  44802. this._vertexData[offset + 11] = particle.cellIndex;
  44803. };
  44804. ParticleSystem.prototype._update = function (newParticles) {
  44805. // Update current
  44806. this._alive = this.particles.length > 0;
  44807. this.updateFunction(this.particles);
  44808. // Add new ones
  44809. var worldMatrix;
  44810. if (this.emitter.position) {
  44811. var emitterMesh = this.emitter;
  44812. worldMatrix = emitterMesh.getWorldMatrix();
  44813. }
  44814. else {
  44815. var emitterPosition = this.emitter;
  44816. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  44817. }
  44818. var particle;
  44819. for (var index = 0; index < newParticles; index++) {
  44820. if (this.particles.length === this._capacity) {
  44821. break;
  44822. }
  44823. if (this._stockParticles.length !== 0) {
  44824. particle = this._stockParticles.pop();
  44825. particle.age = 0;
  44826. particle.cellIndex = this.startSpriteCellID;
  44827. }
  44828. else {
  44829. particle = new BABYLON.Particle(this);
  44830. }
  44831. this.particles.push(particle);
  44832. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  44833. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  44834. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  44835. particle.size = randomNumber(this.minSize, this.maxSize);
  44836. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  44837. this.startPositionFunction(worldMatrix, particle.position, particle);
  44838. var step = randomNumber(0, 1.0);
  44839. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  44840. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  44841. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  44842. }
  44843. };
  44844. ParticleSystem.prototype._getEffect = function () {
  44845. if (this._customEffect) {
  44846. return this._customEffect;
  44847. }
  44848. ;
  44849. var defines = [];
  44850. if (this._scene.clipPlane) {
  44851. defines.push("#define CLIPPLANE");
  44852. }
  44853. if (this._isAnimationSheetEnabled) {
  44854. defines.push("#define ANIMATESHEET");
  44855. }
  44856. // Effect
  44857. var join = defines.join("\n");
  44858. if (this._cachedDefines !== join) {
  44859. this._cachedDefines = join;
  44860. var attributesNamesOrOptions;
  44861. var effectCreationOption;
  44862. if (this._isAnimationSheetEnabled) {
  44863. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  44864. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  44865. }
  44866. else {
  44867. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  44868. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  44869. }
  44870. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  44871. }
  44872. return this._effect;
  44873. };
  44874. ParticleSystem.prototype.animate = function () {
  44875. if (!this._started)
  44876. return;
  44877. var effect = this._getEffect();
  44878. // Check
  44879. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  44880. return;
  44881. if (this._currentRenderId === this._scene.getRenderId()) {
  44882. return;
  44883. }
  44884. this._currentRenderId = this._scene.getRenderId();
  44885. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  44886. // determine the number of particles we need to create
  44887. var newParticles;
  44888. if (this.manualEmitCount > -1) {
  44889. newParticles = this.manualEmitCount;
  44890. this._newPartsExcess = 0;
  44891. this.manualEmitCount = 0;
  44892. }
  44893. else {
  44894. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  44895. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  44896. }
  44897. if (this._newPartsExcess > 1.0) {
  44898. newParticles += this._newPartsExcess >> 0;
  44899. this._newPartsExcess -= this._newPartsExcess >> 0;
  44900. }
  44901. this._alive = false;
  44902. if (!this._stopped) {
  44903. this._actualFrame += this._scaledUpdateSpeed;
  44904. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  44905. this.stop();
  44906. }
  44907. else {
  44908. newParticles = 0;
  44909. }
  44910. this._update(newParticles);
  44911. // Stopped?
  44912. if (this._stopped) {
  44913. if (!this._alive) {
  44914. this._started = false;
  44915. if (this.onAnimationEnd) {
  44916. this.onAnimationEnd();
  44917. }
  44918. if (this.disposeOnStop) {
  44919. this._scene._toBeDisposed.push(this);
  44920. }
  44921. }
  44922. }
  44923. // Animation sheet
  44924. if (this._isAnimationSheetEnabled) {
  44925. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  44926. }
  44927. else {
  44928. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  44929. }
  44930. // Update VBO
  44931. var offset = 0;
  44932. for (var index = 0; index < this.particles.length; index++) {
  44933. var particle = this.particles[index];
  44934. this.appendParticleVertexes(offset, particle);
  44935. offset += 4;
  44936. }
  44937. if (this._vertexBuffer) {
  44938. this._vertexBuffer.update(this._vertexData);
  44939. }
  44940. };
  44941. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  44942. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  44943. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  44944. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  44945. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  44946. };
  44947. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  44948. this._appendParticleVertex(offset++, particle, 0, 0);
  44949. this._appendParticleVertex(offset++, particle, 1, 0);
  44950. this._appendParticleVertex(offset++, particle, 1, 1);
  44951. this._appendParticleVertex(offset++, particle, 0, 1);
  44952. };
  44953. ParticleSystem.prototype.rebuild = function () {
  44954. this._createIndexBuffer();
  44955. if (this._vertexBuffer) {
  44956. this._vertexBuffer._rebuild();
  44957. }
  44958. };
  44959. ParticleSystem.prototype.render = function () {
  44960. var effect = this._getEffect();
  44961. // Check
  44962. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  44963. return 0;
  44964. var engine = this._scene.getEngine();
  44965. // Render
  44966. engine.enableEffect(effect);
  44967. engine.setState(false);
  44968. var viewMatrix = this._scene.getViewMatrix();
  44969. effect.setTexture("diffuseSampler", this.particleTexture);
  44970. effect.setMatrix("view", viewMatrix);
  44971. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  44972. if (this._isAnimationSheetEnabled) {
  44973. var baseSize = this.particleTexture.getBaseSize();
  44974. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  44975. }
  44976. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  44977. if (this._scene.clipPlane) {
  44978. var clipPlane = this._scene.clipPlane;
  44979. var invView = viewMatrix.clone();
  44980. invView.invert();
  44981. effect.setMatrix("invView", invView);
  44982. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  44983. }
  44984. // VBOs
  44985. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  44986. // Draw order
  44987. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  44988. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  44989. }
  44990. else {
  44991. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44992. }
  44993. if (this.forceDepthWrite) {
  44994. engine.setDepthWrite(true);
  44995. }
  44996. engine.draw(true, 0, this.particles.length * 6);
  44997. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  44998. return this.particles.length;
  44999. };
  45000. ParticleSystem.prototype.dispose = function () {
  45001. if (this._vertexBuffer) {
  45002. this._vertexBuffer.dispose();
  45003. this._vertexBuffer = null;
  45004. }
  45005. if (this._indexBuffer) {
  45006. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  45007. this._indexBuffer = null;
  45008. }
  45009. if (this.particleTexture) {
  45010. this.particleTexture.dispose();
  45011. this.particleTexture = null;
  45012. }
  45013. // Remove from scene
  45014. var index = this._scene.particleSystems.indexOf(this);
  45015. if (index > -1) {
  45016. this._scene.particleSystems.splice(index, 1);
  45017. }
  45018. // Callback
  45019. this.onDisposeObservable.notifyObservers(this);
  45020. this.onDisposeObservable.clear();
  45021. };
  45022. // Clone
  45023. ParticleSystem.prototype.clone = function (name, newEmitter) {
  45024. var custom = null;
  45025. var program = null;
  45026. if (this.customShader != null) {
  45027. program = this.customShader;
  45028. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  45029. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  45030. }
  45031. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  45032. result.customShader = program;
  45033. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  45034. if (newEmitter === undefined) {
  45035. newEmitter = this.emitter;
  45036. }
  45037. result.emitter = newEmitter;
  45038. if (this.particleTexture) {
  45039. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  45040. }
  45041. if (!this.preventAutoStart) {
  45042. result.start();
  45043. }
  45044. return result;
  45045. };
  45046. ParticleSystem.prototype.serialize = function () {
  45047. var serializationObject = {};
  45048. serializationObject.name = this.name;
  45049. serializationObject.id = this.id;
  45050. // Emitter
  45051. if (this.emitter.position) {
  45052. var emitterMesh = this.emitter;
  45053. serializationObject.emitterId = emitterMesh.id;
  45054. }
  45055. else {
  45056. var emitterPosition = this.emitter;
  45057. serializationObject.emitter = emitterPosition.asArray();
  45058. }
  45059. serializationObject.capacity = this.getCapacity();
  45060. if (this.particleTexture) {
  45061. serializationObject.textureName = this.particleTexture.name;
  45062. }
  45063. // Animations
  45064. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  45065. // Particle system
  45066. serializationObject.minAngularSpeed = this.minAngularSpeed;
  45067. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  45068. serializationObject.minSize = this.minSize;
  45069. serializationObject.maxSize = this.maxSize;
  45070. serializationObject.minEmitPower = this.minEmitPower;
  45071. serializationObject.maxEmitPower = this.maxEmitPower;
  45072. serializationObject.minLifeTime = this.minLifeTime;
  45073. serializationObject.maxLifeTime = this.maxLifeTime;
  45074. serializationObject.emitRate = this.emitRate;
  45075. serializationObject.minEmitBox = this.minEmitBox.asArray();
  45076. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  45077. serializationObject.gravity = this.gravity.asArray();
  45078. serializationObject.direction1 = this.direction1.asArray();
  45079. serializationObject.direction2 = this.direction2.asArray();
  45080. serializationObject.color1 = this.color1.asArray();
  45081. serializationObject.color2 = this.color2.asArray();
  45082. serializationObject.colorDead = this.colorDead.asArray();
  45083. serializationObject.updateSpeed = this.updateSpeed;
  45084. serializationObject.targetStopDuration = this.targetStopDuration;
  45085. serializationObject.textureMask = this.textureMask.asArray();
  45086. serializationObject.blendMode = this.blendMode;
  45087. serializationObject.customShader = this.customShader;
  45088. serializationObject.preventAutoStart = this.preventAutoStart;
  45089. return serializationObject;
  45090. };
  45091. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  45092. var name = parsedParticleSystem.name;
  45093. var custom = null;
  45094. var program = null;
  45095. if (parsedParticleSystem.customShader) {
  45096. program = parsedParticleSystem.customShader;
  45097. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  45098. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  45099. }
  45100. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  45101. particleSystem.customShader = program;
  45102. if (parsedParticleSystem.id) {
  45103. particleSystem.id = parsedParticleSystem.id;
  45104. }
  45105. // Auto start
  45106. if (parsedParticleSystem.preventAutoStart) {
  45107. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  45108. }
  45109. // Texture
  45110. if (parsedParticleSystem.textureName) {
  45111. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  45112. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  45113. }
  45114. // Emitter
  45115. if (parsedParticleSystem.emitterId) {
  45116. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  45117. }
  45118. else {
  45119. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  45120. }
  45121. // Animations
  45122. if (parsedParticleSystem.animations) {
  45123. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  45124. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  45125. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  45126. }
  45127. }
  45128. if (parsedParticleSystem.autoAnimate) {
  45129. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  45130. }
  45131. // Particle system
  45132. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  45133. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  45134. particleSystem.minSize = parsedParticleSystem.minSize;
  45135. particleSystem.maxSize = parsedParticleSystem.maxSize;
  45136. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  45137. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  45138. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  45139. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  45140. particleSystem.emitRate = parsedParticleSystem.emitRate;
  45141. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  45142. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  45143. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  45144. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  45145. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  45146. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  45147. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  45148. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  45149. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  45150. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  45151. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  45152. particleSystem.blendMode = parsedParticleSystem.blendMode;
  45153. if (!particleSystem.preventAutoStart) {
  45154. particleSystem.start();
  45155. }
  45156. return particleSystem;
  45157. };
  45158. // Statics
  45159. ParticleSystem.BLENDMODE_ONEONE = 0;
  45160. ParticleSystem.BLENDMODE_STANDARD = 1;
  45161. return ParticleSystem;
  45162. }());
  45163. BABYLON.ParticleSystem = ParticleSystem;
  45164. })(BABYLON || (BABYLON = {}));
  45165. //# sourceMappingURL=babylon.particleSystem.js.map
  45166. var BABYLON;
  45167. (function (BABYLON) {
  45168. var SolidParticle = /** @class */ (function () {
  45169. /**
  45170. * Creates a Solid Particle object.
  45171. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  45172. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  45173. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  45174. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  45175. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  45176. * `shapeId` (integer) is the model shape identifier in the SPS.
  45177. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  45178. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  45179. */
  45180. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  45181. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  45182. this.idx = 0; // particle global index
  45183. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  45184. this.position = BABYLON.Vector3.Zero(); // position
  45185. this.rotation = BABYLON.Vector3.Zero(); // rotation
  45186. this.scaling = BABYLON.Vector3.One(); // scaling
  45187. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  45188. this.velocity = BABYLON.Vector3.Zero(); // velocity
  45189. this.pivot = BABYLON.Vector3.Zero(); // pivot point in the particle local space
  45190. this.alive = true; // alive
  45191. this.isVisible = true; // visibility
  45192. this._pos = 0; // index of this particle in the global "positions" array
  45193. this._ind = 0; // index of this particle in the global "indices" array
  45194. this.shapeId = 0; // model shape id
  45195. this.idxInShape = 0; // index of the particle in its shape id
  45196. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  45197. this.idx = particleIndex;
  45198. this._pos = positionIndex;
  45199. this._ind = indiceIndex;
  45200. this._model = model;
  45201. this.shapeId = shapeId;
  45202. this.idxInShape = idxInShape;
  45203. this._sps = sps;
  45204. if (modelBoundingInfo) {
  45205. this._modelBoundingInfo = modelBoundingInfo;
  45206. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  45207. }
  45208. }
  45209. Object.defineProperty(SolidParticle.prototype, "scale", {
  45210. /**
  45211. * legacy support, changed scale to scaling
  45212. */
  45213. get: function () {
  45214. return this.scaling;
  45215. },
  45216. set: function (scale) {
  45217. this.scaling = scale;
  45218. },
  45219. enumerable: true,
  45220. configurable: true
  45221. });
  45222. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  45223. /**
  45224. * legacy support, changed quaternion to rotationQuaternion
  45225. */
  45226. get: function () {
  45227. return this.rotationQuaternion;
  45228. },
  45229. set: function (q) {
  45230. this.rotationQuaternion = q;
  45231. },
  45232. enumerable: true,
  45233. configurable: true
  45234. });
  45235. /**
  45236. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  45237. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  45238. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  45239. */
  45240. SolidParticle.prototype.intersectsMesh = function (target) {
  45241. if (!this._boundingInfo || !target._boundingInfo) {
  45242. return false;
  45243. }
  45244. if (this._sps._bSphereOnly) {
  45245. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  45246. }
  45247. return this._boundingInfo.intersects(target._boundingInfo, false);
  45248. };
  45249. return SolidParticle;
  45250. }());
  45251. BABYLON.SolidParticle = SolidParticle;
  45252. var ModelShape = /** @class */ (function () {
  45253. /**
  45254. * 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.
  45255. * SPS internal tool, don't use it manually.
  45256. */
  45257. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  45258. this._indicesLength = 0; // length of the shape in the model indices array
  45259. this.shapeID = id;
  45260. this._shape = shape;
  45261. this._indicesLength = indicesLength;
  45262. this._shapeUV = shapeUV;
  45263. this._positionFunction = posFunction;
  45264. this._vertexFunction = vtxFunction;
  45265. }
  45266. return ModelShape;
  45267. }());
  45268. BABYLON.ModelShape = ModelShape;
  45269. var DepthSortedParticle = /** @class */ (function () {
  45270. function DepthSortedParticle() {
  45271. this.ind = 0; // index of the particle in the "indices" array
  45272. this.indicesLength = 0; // length of the particle shape in the "indices" array
  45273. this.sqDistance = 0.0; // squared distance from the particle to the camera
  45274. }
  45275. return DepthSortedParticle;
  45276. }());
  45277. BABYLON.DepthSortedParticle = DepthSortedParticle;
  45278. })(BABYLON || (BABYLON = {}));
  45279. //# sourceMappingURL=babylon.solidParticle.js.map
  45280. var BABYLON;
  45281. (function (BABYLON) {
  45282. /**
  45283. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  45284. */
  45285. var SolidParticleSystem = /** @class */ (function () {
  45286. /**
  45287. * Creates a SPS (Solid Particle System) object.
  45288. * `name` (String) is the SPS name, this will be the underlying mesh name.
  45289. * `scene` (Scene) is the scene in which the SPS is added.
  45290. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  45291. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  45292. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  45293. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  45294. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  45295. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  45296. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  45297. */
  45298. function SolidParticleSystem(name, scene, options) {
  45299. // public members
  45300. /**
  45301. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  45302. * Example : var p = SPS.particles[i];
  45303. */
  45304. this.particles = new Array();
  45305. /**
  45306. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  45307. */
  45308. this.nbParticles = 0;
  45309. /**
  45310. * If the particles must ever face the camera (default false). Useful for planar particles.
  45311. */
  45312. this.billboard = false;
  45313. /**
  45314. * Recompute normals when adding a shape
  45315. */
  45316. this.recomputeNormals = true;
  45317. /**
  45318. * This a counter ofr your own usage. It's not set by any SPS functions.
  45319. */
  45320. this.counter = 0;
  45321. /**
  45322. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  45323. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  45324. */
  45325. this.vars = {};
  45326. this._positions = new Array();
  45327. this._indices = new Array();
  45328. this._normals = new Array();
  45329. this._colors = new Array();
  45330. this._uvs = new Array();
  45331. this._index = 0; // indices index
  45332. this._updatable = true;
  45333. this._pickable = false;
  45334. this._isVisibilityBoxLocked = false;
  45335. this._alwaysVisible = false;
  45336. this._depthSort = false;
  45337. this._shapeCounter = 0;
  45338. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  45339. this._color = new BABYLON.Color4(0, 0, 0, 0);
  45340. this._computeParticleColor = true;
  45341. this._computeParticleTexture = true;
  45342. this._computeParticleRotation = true;
  45343. this._computeParticleVertex = false;
  45344. this._computeBoundingBox = false;
  45345. this._depthSortParticles = true;
  45346. this._cam_axisZ = BABYLON.Vector3.Zero();
  45347. this._cam_axisY = BABYLON.Vector3.Zero();
  45348. this._cam_axisX = BABYLON.Vector3.Zero();
  45349. this._axisZ = BABYLON.Axis.Z;
  45350. this._camDir = BABYLON.Vector3.Zero();
  45351. this._camInvertedPosition = BABYLON.Vector3.Zero();
  45352. this._rotMatrix = new BABYLON.Matrix();
  45353. this._invertMatrix = new BABYLON.Matrix();
  45354. this._rotated = BABYLON.Vector3.Zero();
  45355. this._quaternion = new BABYLON.Quaternion();
  45356. this._vertex = BABYLON.Vector3.Zero();
  45357. this._normal = BABYLON.Vector3.Zero();
  45358. this._yaw = 0.0;
  45359. this._pitch = 0.0;
  45360. this._roll = 0.0;
  45361. this._halfroll = 0.0;
  45362. this._halfpitch = 0.0;
  45363. this._halfyaw = 0.0;
  45364. this._sinRoll = 0.0;
  45365. this._cosRoll = 0.0;
  45366. this._sinPitch = 0.0;
  45367. this._cosPitch = 0.0;
  45368. this._sinYaw = 0.0;
  45369. this._cosYaw = 0.0;
  45370. this._mustUnrotateFixedNormals = false;
  45371. this._minimum = BABYLON.Tmp.Vector3[0];
  45372. this._maximum = BABYLON.Tmp.Vector3[1];
  45373. this._minBbox = BABYLON.Tmp.Vector3[4];
  45374. this._maxBbox = BABYLON.Tmp.Vector3[5];
  45375. this._particlesIntersect = false;
  45376. this._depthSortFunction = function (p1, p2) {
  45377. return (p2.sqDistance - p1.sqDistance);
  45378. };
  45379. this._needs32Bits = false;
  45380. this._bSphereOnly = false;
  45381. this._bSphereRadiusFactor = 1.0;
  45382. this.name = name;
  45383. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  45384. this._camera = scene.activeCamera;
  45385. this._pickable = options ? options.isPickable : false;
  45386. this._depthSort = options ? options.enableDepthSort : false;
  45387. this._particlesIntersect = options ? options.particleIntersection : false;
  45388. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  45389. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  45390. if (options && options.updatable) {
  45391. this._updatable = options.updatable;
  45392. }
  45393. else {
  45394. this._updatable = true;
  45395. }
  45396. if (this._pickable) {
  45397. this.pickedParticles = [];
  45398. }
  45399. if (this._depthSort) {
  45400. this.depthSortedParticles = [];
  45401. }
  45402. }
  45403. /**
  45404. * Builds the SPS underlying mesh. Returns a standard Mesh.
  45405. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  45406. */
  45407. SolidParticleSystem.prototype.buildMesh = function () {
  45408. if (this.nbParticles === 0) {
  45409. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  45410. this.addShape(triangle, 1);
  45411. triangle.dispose();
  45412. }
  45413. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  45414. this._positions32 = new Float32Array(this._positions);
  45415. this._uvs32 = new Float32Array(this._uvs);
  45416. this._colors32 = new Float32Array(this._colors);
  45417. if (this.recomputeNormals) {
  45418. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  45419. }
  45420. this._normals32 = new Float32Array(this._normals);
  45421. this._fixedNormal32 = new Float32Array(this._normals);
  45422. if (this._mustUnrotateFixedNormals) {
  45423. this._unrotateFixedNormals();
  45424. }
  45425. var vertexData = new BABYLON.VertexData();
  45426. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  45427. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  45428. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  45429. if (this._uvs32) {
  45430. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  45431. ;
  45432. }
  45433. if (this._colors32) {
  45434. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  45435. }
  45436. var mesh = new BABYLON.Mesh(this.name, this._scene);
  45437. vertexData.applyToMesh(mesh, this._updatable);
  45438. this.mesh = mesh;
  45439. this.mesh.isPickable = this._pickable;
  45440. // free memory
  45441. if (!this._depthSort) {
  45442. this._indices = null;
  45443. }
  45444. this._positions = null;
  45445. this._normals = null;
  45446. this._uvs = null;
  45447. this._colors = null;
  45448. if (!this._updatable) {
  45449. this.particles.length = 0;
  45450. }
  45451. return mesh;
  45452. };
  45453. /**
  45454. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  45455. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  45456. * Thus the particles generated from `digest()` have their property `position` set yet.
  45457. * `mesh` ( Mesh ) is the mesh to be digested
  45458. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  45459. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  45460. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  45461. */
  45462. SolidParticleSystem.prototype.digest = function (mesh, options) {
  45463. var size = (options && options.facetNb) || 1;
  45464. var number = (options && options.number) || 0;
  45465. var delta = (options && options.delta) || 0;
  45466. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45467. var meshInd = mesh.getIndices();
  45468. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45469. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  45470. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45471. var f = 0; // facet counter
  45472. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  45473. // compute size from number
  45474. if (number) {
  45475. number = (number > totalFacets) ? totalFacets : number;
  45476. size = Math.round(totalFacets / number);
  45477. delta = 0;
  45478. }
  45479. else {
  45480. size = (size > totalFacets) ? totalFacets : size;
  45481. }
  45482. var facetPos = []; // submesh positions
  45483. var facetInd = []; // submesh indices
  45484. var facetUV = []; // submesh UV
  45485. var facetCol = []; // submesh colors
  45486. var barycenter = BABYLON.Tmp.Vector3[0];
  45487. var sizeO = size;
  45488. while (f < totalFacets) {
  45489. size = sizeO + Math.floor((1 + delta) * Math.random());
  45490. if (f > totalFacets - size) {
  45491. size = totalFacets - f;
  45492. }
  45493. // reset temp arrays
  45494. facetPos.length = 0;
  45495. facetInd.length = 0;
  45496. facetUV.length = 0;
  45497. facetCol.length = 0;
  45498. // iterate over "size" facets
  45499. var fi = 0;
  45500. for (var j = f * 3; j < (f + size) * 3; j++) {
  45501. facetInd.push(fi);
  45502. var i = meshInd[j];
  45503. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  45504. if (meshUV) {
  45505. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  45506. }
  45507. if (meshCol) {
  45508. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  45509. }
  45510. fi++;
  45511. }
  45512. // create a model shape for each single particle
  45513. var idx = this.nbParticles;
  45514. var shape = this._posToShape(facetPos);
  45515. var shapeUV = this._uvsToShapeUV(facetUV);
  45516. // compute the barycenter of the shape
  45517. var v;
  45518. for (v = 0; v < shape.length; v++) {
  45519. barycenter.addInPlace(shape[v]);
  45520. }
  45521. barycenter.scaleInPlace(1 / shape.length);
  45522. // shift the shape from its barycenter to the origin
  45523. for (v = 0; v < shape.length; v++) {
  45524. shape[v].subtractInPlace(barycenter);
  45525. }
  45526. var bInfo;
  45527. if (this._particlesIntersect) {
  45528. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  45529. }
  45530. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  45531. // add the particle in the SPS
  45532. var currentPos = this._positions.length;
  45533. var currentInd = this._indices.length;
  45534. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  45535. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  45536. // initialize the particle position
  45537. this.particles[this.nbParticles].position.addInPlace(barycenter);
  45538. this._index += shape.length;
  45539. idx++;
  45540. this.nbParticles++;
  45541. this._shapeCounter++;
  45542. f += size;
  45543. }
  45544. return this;
  45545. };
  45546. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  45547. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  45548. var index = 0;
  45549. var idx = 0;
  45550. for (var p = 0; p < this.particles.length; p++) {
  45551. this._particle = this.particles[p];
  45552. this._shape = this._particle._model._shape;
  45553. if (this._particle.rotationQuaternion) {
  45554. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  45555. }
  45556. else {
  45557. this._yaw = this._particle.rotation.y;
  45558. this._pitch = this._particle.rotation.x;
  45559. this._roll = this._particle.rotation.z;
  45560. this._quaternionRotationYPR();
  45561. }
  45562. this._quaternionToRotationMatrix();
  45563. this._rotMatrix.invertToRef(this._invertMatrix);
  45564. for (var pt = 0; pt < this._shape.length; pt++) {
  45565. idx = index + pt * 3;
  45566. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  45567. this._fixedNormal32[idx] = this._normal.x;
  45568. this._fixedNormal32[idx + 1] = this._normal.y;
  45569. this._fixedNormal32[idx + 2] = this._normal.z;
  45570. }
  45571. index = idx + 3;
  45572. }
  45573. };
  45574. //reset copy
  45575. SolidParticleSystem.prototype._resetCopy = function () {
  45576. this._copy.position.x = 0;
  45577. this._copy.position.y = 0;
  45578. this._copy.position.z = 0;
  45579. this._copy.rotation.x = 0;
  45580. this._copy.rotation.y = 0;
  45581. this._copy.rotation.z = 0;
  45582. this._copy.rotationQuaternion = null;
  45583. this._copy.scaling.x = 1.0;
  45584. this._copy.scaling.y = 1.0;
  45585. this._copy.scaling.z = 1.0;
  45586. this._copy.uvs.x = 0;
  45587. this._copy.uvs.y = 0;
  45588. this._copy.uvs.z = 1.0;
  45589. this._copy.uvs.w = 1.0;
  45590. this._copy.color = null;
  45591. };
  45592. // _meshBuilder : inserts the shape model in the global SPS mesh
  45593. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  45594. var i;
  45595. var u = 0;
  45596. var c = 0;
  45597. var n = 0;
  45598. this._resetCopy();
  45599. if (options && options.positionFunction) {
  45600. options.positionFunction(this._copy, idx, idxInShape);
  45601. this._mustUnrotateFixedNormals = true;
  45602. }
  45603. if (this._copy.rotationQuaternion) {
  45604. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  45605. }
  45606. else {
  45607. this._yaw = this._copy.rotation.y;
  45608. this._pitch = this._copy.rotation.x;
  45609. this._roll = this._copy.rotation.z;
  45610. this._quaternionRotationYPR();
  45611. }
  45612. this._quaternionToRotationMatrix();
  45613. for (i = 0; i < shape.length; i++) {
  45614. this._vertex.x = shape[i].x;
  45615. this._vertex.y = shape[i].y;
  45616. this._vertex.z = shape[i].z;
  45617. if (options && options.vertexFunction) {
  45618. options.vertexFunction(this._copy, this._vertex, i);
  45619. }
  45620. this._vertex.x *= this._copy.scaling.x;
  45621. this._vertex.y *= this._copy.scaling.y;
  45622. this._vertex.z *= this._copy.scaling.z;
  45623. this._vertex.x += this._copy.pivot.x;
  45624. this._vertex.y += this._copy.pivot.y;
  45625. this._vertex.z += this._copy.pivot.z;
  45626. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  45627. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  45628. if (meshUV) {
  45629. 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);
  45630. u += 2;
  45631. }
  45632. if (this._copy.color) {
  45633. this._color = this._copy.color;
  45634. }
  45635. else if (meshCol && meshCol[c] !== undefined) {
  45636. this._color.r = meshCol[c];
  45637. this._color.g = meshCol[c + 1];
  45638. this._color.b = meshCol[c + 2];
  45639. this._color.a = meshCol[c + 3];
  45640. }
  45641. else {
  45642. this._color.r = 1.0;
  45643. this._color.g = 1.0;
  45644. this._color.b = 1.0;
  45645. this._color.a = 1.0;
  45646. }
  45647. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  45648. c += 4;
  45649. if (!this.recomputeNormals && meshNor) {
  45650. this._normal.x = meshNor[n];
  45651. this._normal.y = meshNor[n + 1];
  45652. this._normal.z = meshNor[n + 2];
  45653. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  45654. normals.push(this._normal.x, this._normal.y, this._normal.z);
  45655. n += 3;
  45656. }
  45657. }
  45658. for (i = 0; i < meshInd.length; i++) {
  45659. var current_ind = p + meshInd[i];
  45660. indices.push(current_ind);
  45661. if (current_ind > 65535) {
  45662. this._needs32Bits = true;
  45663. }
  45664. }
  45665. if (this._pickable) {
  45666. var nbfaces = meshInd.length / 3;
  45667. for (i = 0; i < nbfaces; i++) {
  45668. this.pickedParticles.push({ idx: idx, faceId: i });
  45669. }
  45670. }
  45671. if (this._depthSort) {
  45672. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  45673. }
  45674. return this._copy;
  45675. };
  45676. // returns a shape array from positions array
  45677. SolidParticleSystem.prototype._posToShape = function (positions) {
  45678. var shape = [];
  45679. for (var i = 0; i < positions.length; i += 3) {
  45680. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  45681. }
  45682. return shape;
  45683. };
  45684. // returns a shapeUV array from a Vector4 uvs
  45685. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  45686. var shapeUV = [];
  45687. if (uvs) {
  45688. for (var i = 0; i < uvs.length; i++)
  45689. shapeUV.push(uvs[i]);
  45690. }
  45691. return shapeUV;
  45692. };
  45693. // adds a new particle object in the particles array
  45694. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  45695. if (bInfo === void 0) { bInfo = null; }
  45696. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  45697. this.particles.push(sp);
  45698. return sp;
  45699. };
  45700. /**
  45701. * Adds some particles to the SPS from the model shape. Returns the shape id.
  45702. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  45703. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  45704. * `nb` (positive integer) the number of particles to be created from this model
  45705. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  45706. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  45707. */
  45708. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  45709. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45710. var meshInd = mesh.getIndices();
  45711. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45712. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  45713. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45714. var bbInfo;
  45715. if (this._particlesIntersect) {
  45716. bbInfo = mesh.getBoundingInfo();
  45717. }
  45718. var shape = this._posToShape(meshPos);
  45719. var shapeUV = this._uvsToShapeUV(meshUV);
  45720. var posfunc = options ? options.positionFunction : null;
  45721. var vtxfunc = options ? options.vertexFunction : null;
  45722. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  45723. // particles
  45724. var sp;
  45725. var currentCopy;
  45726. var idx = this.nbParticles;
  45727. for (var i = 0; i < nb; i++) {
  45728. var currentPos = this._positions.length;
  45729. var currentInd = this._indices.length;
  45730. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  45731. if (this._updatable) {
  45732. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  45733. sp.position.copyFrom(currentCopy.position);
  45734. sp.rotation.copyFrom(currentCopy.rotation);
  45735. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  45736. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  45737. }
  45738. if (currentCopy.color && sp.color) {
  45739. sp.color.copyFrom(currentCopy.color);
  45740. }
  45741. sp.scaling.copyFrom(currentCopy.scaling);
  45742. sp.uvs.copyFrom(currentCopy.uvs);
  45743. }
  45744. this._index += shape.length;
  45745. idx++;
  45746. }
  45747. this.nbParticles += nb;
  45748. this._shapeCounter++;
  45749. return this._shapeCounter - 1;
  45750. };
  45751. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  45752. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  45753. this._resetCopy();
  45754. if (particle._model._positionFunction) {
  45755. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  45756. }
  45757. if (this._copy.rotationQuaternion) {
  45758. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  45759. }
  45760. else {
  45761. this._yaw = this._copy.rotation.y;
  45762. this._pitch = this._copy.rotation.x;
  45763. this._roll = this._copy.rotation.z;
  45764. this._quaternionRotationYPR();
  45765. }
  45766. this._quaternionToRotationMatrix();
  45767. this._shape = particle._model._shape;
  45768. for (var pt = 0; pt < this._shape.length; pt++) {
  45769. this._vertex.x = this._shape[pt].x;
  45770. this._vertex.y = this._shape[pt].y;
  45771. this._vertex.z = this._shape[pt].z;
  45772. if (particle._model._vertexFunction) {
  45773. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  45774. }
  45775. this._vertex.x *= this._copy.scaling.x;
  45776. this._vertex.y *= this._copy.scaling.y;
  45777. this._vertex.z *= this._copy.scaling.z;
  45778. this._vertex.x += this._copy.pivot.x;
  45779. this._vertex.y += this._copy.pivot.y;
  45780. this._vertex.z += this._copy.pivot.z;
  45781. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  45782. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  45783. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  45784. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  45785. }
  45786. particle.position.x = 0.0;
  45787. particle.position.y = 0.0;
  45788. particle.position.z = 0.0;
  45789. particle.rotation.x = 0.0;
  45790. particle.rotation.y = 0.0;
  45791. particle.rotation.z = 0.0;
  45792. particle.rotationQuaternion = null;
  45793. particle.scaling.x = 1.0;
  45794. particle.scaling.y = 1.0;
  45795. particle.scaling.z = 1.0;
  45796. };
  45797. /**
  45798. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  45799. * Returns the SPS.
  45800. */
  45801. SolidParticleSystem.prototype.rebuildMesh = function () {
  45802. for (var p = 0; p < this.particles.length; p++) {
  45803. this._rebuildParticle(this.particles[p]);
  45804. }
  45805. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  45806. return this;
  45807. };
  45808. /**
  45809. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  45810. * This method calls `updateParticle()` for each particle of the SPS.
  45811. * For an animated SPS, it is usually called within the render loop.
  45812. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  45813. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  45814. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  45815. * Returns the SPS.
  45816. */
  45817. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  45818. if (start === void 0) { start = 0; }
  45819. if (end === void 0) { end = this.nbParticles - 1; }
  45820. if (update === void 0) { update = true; }
  45821. if (!this._updatable) {
  45822. return this;
  45823. }
  45824. // custom beforeUpdate
  45825. this.beforeUpdateParticles(start, end, update);
  45826. this._cam_axisX.x = 1.0;
  45827. this._cam_axisX.y = 0.0;
  45828. this._cam_axisX.z = 0.0;
  45829. this._cam_axisY.x = 0.0;
  45830. this._cam_axisY.y = 1.0;
  45831. this._cam_axisY.z = 0.0;
  45832. this._cam_axisZ.x = 0.0;
  45833. this._cam_axisZ.y = 0.0;
  45834. this._cam_axisZ.z = 1.0;
  45835. // cases when the World Matrix is to be computed first
  45836. if (this.billboard || this._depthSort) {
  45837. this.mesh.computeWorldMatrix(true);
  45838. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  45839. }
  45840. // if the particles will always face the camera
  45841. if (this.billboard) {
  45842. // compute the camera position and un-rotate it by the current mesh rotation
  45843. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  45844. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  45845. this._cam_axisZ.normalize();
  45846. // same for camera up vector extracted from the cam view matrix
  45847. var view = this._camera.getViewMatrix(true);
  45848. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  45849. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  45850. this._cam_axisY.normalize();
  45851. this._cam_axisX.normalize();
  45852. }
  45853. // if depthSort, compute the camera global position in the mesh local system
  45854. if (this._depthSort) {
  45855. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  45856. }
  45857. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  45858. var idx = 0; // current position index in the global array positions32
  45859. var index = 0; // position start index in the global array positions32 of the current particle
  45860. var colidx = 0; // current color index in the global array colors32
  45861. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  45862. var uvidx = 0; // current uv index in the global array uvs32
  45863. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  45864. var pt = 0; // current index in the particle model shape
  45865. if (this.mesh.isFacetDataEnabled) {
  45866. this._computeBoundingBox = true;
  45867. }
  45868. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  45869. if (this._computeBoundingBox) {
  45870. if (start == 0 && end == this.nbParticles - 1) {
  45871. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  45872. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  45873. }
  45874. else {
  45875. if (this.mesh._boundingInfo) {
  45876. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  45877. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  45878. }
  45879. }
  45880. }
  45881. // particle loop
  45882. index = this.particles[start]._pos;
  45883. var vpos = (index / 3) | 0;
  45884. colorIndex = vpos * 4;
  45885. uvIndex = vpos * 2;
  45886. for (var p = start; p <= end; p++) {
  45887. this._particle = this.particles[p];
  45888. this._shape = this._particle._model._shape;
  45889. this._shapeUV = this._particle._model._shapeUV;
  45890. // call to custom user function to update the particle properties
  45891. this.updateParticle(this._particle);
  45892. // camera-particle distance for depth sorting
  45893. if (this._depthSort && this._depthSortParticles) {
  45894. var dsp = this.depthSortedParticles[p];
  45895. dsp.ind = this._particle._ind;
  45896. dsp.indicesLength = this._particle._model._indicesLength;
  45897. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  45898. }
  45899. // skip the computations for inactive or already invisible particles
  45900. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  45901. // increment indexes for the next particle
  45902. pt = this._shape.length;
  45903. index += pt * 3;
  45904. colorIndex += pt * 4;
  45905. uvIndex += pt * 2;
  45906. continue;
  45907. }
  45908. if (this._particle.isVisible) {
  45909. this._particle._stillInvisible = false; // un-mark permanent invisibility
  45910. // particle rotation matrix
  45911. if (this.billboard) {
  45912. this._particle.rotation.x = 0.0;
  45913. this._particle.rotation.y = 0.0;
  45914. }
  45915. if (this._computeParticleRotation || this.billboard) {
  45916. if (this._particle.rotationQuaternion) {
  45917. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  45918. }
  45919. else {
  45920. this._yaw = this._particle.rotation.y;
  45921. this._pitch = this._particle.rotation.x;
  45922. this._roll = this._particle.rotation.z;
  45923. this._quaternionRotationYPR();
  45924. }
  45925. this._quaternionToRotationMatrix();
  45926. }
  45927. // particle vertex loop
  45928. for (pt = 0; pt < this._shape.length; pt++) {
  45929. idx = index + pt * 3;
  45930. colidx = colorIndex + pt * 4;
  45931. uvidx = uvIndex + pt * 2;
  45932. this._vertex.x = this._shape[pt].x;
  45933. this._vertex.y = this._shape[pt].y;
  45934. this._vertex.z = this._shape[pt].z;
  45935. if (this._computeParticleVertex) {
  45936. this.updateParticleVertex(this._particle, this._vertex, pt);
  45937. }
  45938. // positions
  45939. this._vertex.x *= this._particle.scaling.x;
  45940. this._vertex.y *= this._particle.scaling.y;
  45941. this._vertex.z *= this._particle.scaling.z;
  45942. this._vertex.x += this._particle.pivot.x;
  45943. this._vertex.y += this._particle.pivot.y;
  45944. this._vertex.z += this._particle.pivot.z;
  45945. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  45946. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  45947. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  45948. 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;
  45949. 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;
  45950. 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;
  45951. if (this._computeBoundingBox) {
  45952. if (this._positions32[idx] < this._minimum.x) {
  45953. this._minimum.x = this._positions32[idx];
  45954. }
  45955. if (this._positions32[idx] > this._maximum.x) {
  45956. this._maximum.x = this._positions32[idx];
  45957. }
  45958. if (this._positions32[idx + 1] < this._minimum.y) {
  45959. this._minimum.y = this._positions32[idx + 1];
  45960. }
  45961. if (this._positions32[idx + 1] > this._maximum.y) {
  45962. this._maximum.y = this._positions32[idx + 1];
  45963. }
  45964. if (this._positions32[idx + 2] < this._minimum.z) {
  45965. this._minimum.z = this._positions32[idx + 2];
  45966. }
  45967. if (this._positions32[idx + 2] > this._maximum.z) {
  45968. this._maximum.z = this._positions32[idx + 2];
  45969. }
  45970. }
  45971. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  45972. if (!this._computeParticleVertex) {
  45973. this._normal.x = this._fixedNormal32[idx];
  45974. this._normal.y = this._fixedNormal32[idx + 1];
  45975. this._normal.z = this._fixedNormal32[idx + 2];
  45976. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  45977. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  45978. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  45979. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  45980. 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;
  45981. 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;
  45982. }
  45983. if (this._computeParticleColor && this._particle.color) {
  45984. this._colors32[colidx] = this._particle.color.r;
  45985. this._colors32[colidx + 1] = this._particle.color.g;
  45986. this._colors32[colidx + 2] = this._particle.color.b;
  45987. this._colors32[colidx + 3] = this._particle.color.a;
  45988. }
  45989. if (this._computeParticleTexture) {
  45990. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  45991. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  45992. }
  45993. }
  45994. }
  45995. else {
  45996. this._particle._stillInvisible = true; // mark the particle as invisible
  45997. for (pt = 0; pt < this._shape.length; pt++) {
  45998. idx = index + pt * 3;
  45999. colidx = colorIndex + pt * 4;
  46000. uvidx = uvIndex + pt * 2;
  46001. this._positions32[idx] = 0.0;
  46002. this._positions32[idx + 1] = 0.0;
  46003. this._positions32[idx + 2] = 0.0;
  46004. this._normals32[idx] = 0.0;
  46005. this._normals32[idx + 1] = 0.0;
  46006. this._normals32[idx + 2] = 0.0;
  46007. if (this._computeParticleColor && this._particle.color) {
  46008. this._colors32[colidx] = this._particle.color.r;
  46009. this._colors32[colidx + 1] = this._particle.color.g;
  46010. this._colors32[colidx + 2] = this._particle.color.b;
  46011. this._colors32[colidx + 3] = this._particle.color.a;
  46012. }
  46013. if (this._computeParticleTexture) {
  46014. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  46015. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  46016. }
  46017. }
  46018. }
  46019. // if the particle intersections must be computed : update the bbInfo
  46020. if (this._particlesIntersect) {
  46021. var bInfo = this._particle._boundingInfo;
  46022. var bBox = bInfo.boundingBox;
  46023. var bSphere = bInfo.boundingSphere;
  46024. if (!this._bSphereOnly) {
  46025. // place, scale and rotate the particle bbox within the SPS local system, then update it
  46026. for (var b = 0; b < bBox.vectors.length; b++) {
  46027. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  46028. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  46029. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  46030. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  46031. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  46032. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  46033. 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;
  46034. 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;
  46035. 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;
  46036. }
  46037. bBox._update(this.mesh._worldMatrix);
  46038. }
  46039. // place and scale the particle bouding sphere in the SPS local system, then update it
  46040. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  46041. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  46042. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  46043. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  46044. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  46045. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  46046. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  46047. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  46048. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  46049. 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));
  46050. bSphere._update(this.mesh._worldMatrix);
  46051. }
  46052. // increment indexes for the next particle
  46053. index = idx + 3;
  46054. colorIndex = colidx + 4;
  46055. uvIndex = uvidx + 2;
  46056. }
  46057. // if the VBO must be updated
  46058. if (update) {
  46059. if (this._computeParticleColor) {
  46060. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  46061. }
  46062. if (this._computeParticleTexture) {
  46063. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  46064. }
  46065. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  46066. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  46067. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  46068. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  46069. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  46070. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  46071. for (var i = 0; i < this._normals32.length; i++) {
  46072. this._fixedNormal32[i] = this._normals32[i];
  46073. }
  46074. }
  46075. if (!this.mesh.areNormalsFrozen) {
  46076. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  46077. }
  46078. }
  46079. if (this._depthSort && this._depthSortParticles) {
  46080. this.depthSortedParticles.sort(this._depthSortFunction);
  46081. var dspl = this.depthSortedParticles.length;
  46082. var sorted = 0;
  46083. var lind = 0;
  46084. var sind = 0;
  46085. var sid = 0;
  46086. for (sorted = 0; sorted < dspl; sorted++) {
  46087. lind = this.depthSortedParticles[sorted].indicesLength;
  46088. sind = this.depthSortedParticles[sorted].ind;
  46089. for (var i = 0; i < lind; i++) {
  46090. this._indices32[sid] = this._indices[sind + i];
  46091. sid++;
  46092. }
  46093. }
  46094. this.mesh.updateIndices(this._indices32);
  46095. }
  46096. }
  46097. if (this._computeBoundingBox) {
  46098. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  46099. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  46100. }
  46101. this.afterUpdateParticles(start, end, update);
  46102. return this;
  46103. };
  46104. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  46105. this._halfroll = this._roll * 0.5;
  46106. this._halfpitch = this._pitch * 0.5;
  46107. this._halfyaw = this._yaw * 0.5;
  46108. this._sinRoll = Math.sin(this._halfroll);
  46109. this._cosRoll = Math.cos(this._halfroll);
  46110. this._sinPitch = Math.sin(this._halfpitch);
  46111. this._cosPitch = Math.cos(this._halfpitch);
  46112. this._sinYaw = Math.sin(this._halfyaw);
  46113. this._cosYaw = Math.cos(this._halfyaw);
  46114. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  46115. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  46116. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  46117. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  46118. };
  46119. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  46120. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  46121. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  46122. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  46123. this._rotMatrix.m[3] = 0;
  46124. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  46125. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  46126. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  46127. this._rotMatrix.m[7] = 0;
  46128. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  46129. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  46130. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  46131. this._rotMatrix.m[11] = 0;
  46132. this._rotMatrix.m[12] = 0;
  46133. this._rotMatrix.m[13] = 0;
  46134. this._rotMatrix.m[14] = 0;
  46135. this._rotMatrix.m[15] = 1.0;
  46136. };
  46137. /**
  46138. * Disposes the SPS.
  46139. * Returns nothing.
  46140. */
  46141. SolidParticleSystem.prototype.dispose = function () {
  46142. this.mesh.dispose();
  46143. this.vars = null;
  46144. // drop references to internal big arrays for the GC
  46145. this._positions = null;
  46146. this._indices = null;
  46147. this._normals = null;
  46148. this._uvs = null;
  46149. this._colors = null;
  46150. this._indices32 = null;
  46151. this._positions32 = null;
  46152. this._normals32 = null;
  46153. this._fixedNormal32 = null;
  46154. this._uvs32 = null;
  46155. this._colors32 = null;
  46156. this.pickedParticles = null;
  46157. };
  46158. /**
  46159. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  46160. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46161. * Returns the SPS.
  46162. */
  46163. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  46164. if (!this._isVisibilityBoxLocked) {
  46165. this.mesh.refreshBoundingInfo();
  46166. }
  46167. return this;
  46168. };
  46169. /**
  46170. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  46171. * @param size the size (float) of the visibility box
  46172. * note : this doesn't lock the SPS mesh bounding box.
  46173. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46174. */
  46175. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  46176. var vis = size / 2;
  46177. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  46178. };
  46179. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  46180. // getter and setter
  46181. get: function () {
  46182. return this._alwaysVisible;
  46183. },
  46184. /**
  46185. * Sets the SPS as always visible or not
  46186. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46187. */
  46188. set: function (val) {
  46189. this._alwaysVisible = val;
  46190. this.mesh.alwaysSelectAsActiveMesh = val;
  46191. },
  46192. enumerable: true,
  46193. configurable: true
  46194. });
  46195. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  46196. get: function () {
  46197. return this._isVisibilityBoxLocked;
  46198. },
  46199. /**
  46200. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  46201. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46202. */
  46203. set: function (val) {
  46204. this._isVisibilityBoxLocked = val;
  46205. var boundingInfo = this.mesh.getBoundingInfo();
  46206. boundingInfo.isLocked = val;
  46207. },
  46208. enumerable: true,
  46209. configurable: true
  46210. });
  46211. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  46212. // getters
  46213. get: function () {
  46214. return this._computeParticleRotation;
  46215. },
  46216. // Optimizer setters
  46217. /**
  46218. * Tells to `setParticles()` to compute the particle rotations or not.
  46219. * Default value : true. The SPS is faster when it's set to false.
  46220. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  46221. */
  46222. set: function (val) {
  46223. this._computeParticleRotation = val;
  46224. },
  46225. enumerable: true,
  46226. configurable: true
  46227. });
  46228. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  46229. get: function () {
  46230. return this._computeParticleColor;
  46231. },
  46232. /**
  46233. * Tells to `setParticles()` to compute the particle colors or not.
  46234. * Default value : true. The SPS is faster when it's set to false.
  46235. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  46236. */
  46237. set: function (val) {
  46238. this._computeParticleColor = val;
  46239. },
  46240. enumerable: true,
  46241. configurable: true
  46242. });
  46243. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  46244. get: function () {
  46245. return this._computeParticleTexture;
  46246. },
  46247. /**
  46248. * Tells to `setParticles()` to compute the particle textures or not.
  46249. * Default value : true. The SPS is faster when it's set to false.
  46250. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  46251. */
  46252. set: function (val) {
  46253. this._computeParticleTexture = val;
  46254. },
  46255. enumerable: true,
  46256. configurable: true
  46257. });
  46258. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  46259. get: function () {
  46260. return this._computeParticleVertex;
  46261. },
  46262. /**
  46263. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  46264. * Default value : false. The SPS is faster when it's set to false.
  46265. * Note : the particle custom vertex positions aren't stored values.
  46266. */
  46267. set: function (val) {
  46268. this._computeParticleVertex = val;
  46269. },
  46270. enumerable: true,
  46271. configurable: true
  46272. });
  46273. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  46274. get: function () {
  46275. return this._computeBoundingBox;
  46276. },
  46277. /**
  46278. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  46279. */
  46280. set: function (val) {
  46281. this._computeBoundingBox = val;
  46282. },
  46283. enumerable: true,
  46284. configurable: true
  46285. });
  46286. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  46287. get: function () {
  46288. return this._depthSortParticles;
  46289. },
  46290. /**
  46291. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  46292. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  46293. * Default : `true`
  46294. */
  46295. set: function (val) {
  46296. this._depthSortParticles = val;
  46297. },
  46298. enumerable: true,
  46299. configurable: true
  46300. });
  46301. // =======================================================================
  46302. // Particle behavior logic
  46303. // these following methods may be overwritten by the user to fit his needs
  46304. /**
  46305. * This function does nothing. It may be overwritten to set all the particle first values.
  46306. * The SPS doesn't call this function, you may have to call it by your own.
  46307. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  46308. */
  46309. SolidParticleSystem.prototype.initParticles = function () {
  46310. };
  46311. /**
  46312. * This function does nothing. It may be overwritten to recycle a particle.
  46313. * The SPS doesn't call this function, you may have to call it by your own.
  46314. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  46315. */
  46316. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  46317. return particle;
  46318. };
  46319. /**
  46320. * Updates a particle : this function should be overwritten by the user.
  46321. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  46322. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  46323. * ex : just set a particle position or velocity and recycle conditions
  46324. */
  46325. SolidParticleSystem.prototype.updateParticle = function (particle) {
  46326. return particle;
  46327. };
  46328. /**
  46329. * Updates a vertex of a particle : it can be overwritten by the user.
  46330. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  46331. * @param particle the current particle
  46332. * @param vertex the current index of the current particle
  46333. * @param pt the index of the current vertex in the particle shape
  46334. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  46335. * ex : just set a vertex particle position
  46336. */
  46337. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  46338. return vertex;
  46339. };
  46340. /**
  46341. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  46342. * This does nothing and may be overwritten by the user.
  46343. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  46344. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  46345. * @param update the boolean update value actually passed to setParticles()
  46346. */
  46347. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  46348. };
  46349. /**
  46350. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  46351. * This will be passed three parameters.
  46352. * This does nothing and may be overwritten by the user.
  46353. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  46354. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  46355. * @param update the boolean update value actually passed to setParticles()
  46356. */
  46357. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  46358. };
  46359. return SolidParticleSystem;
  46360. }());
  46361. BABYLON.SolidParticleSystem = SolidParticleSystem;
  46362. })(BABYLON || (BABYLON = {}));
  46363. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  46364. var BABYLON;
  46365. (function (BABYLON) {
  46366. var GroundMesh = /** @class */ (function (_super) {
  46367. __extends(GroundMesh, _super);
  46368. function GroundMesh(name, scene) {
  46369. var _this = _super.call(this, name, scene) || this;
  46370. _this.generateOctree = false;
  46371. return _this;
  46372. }
  46373. GroundMesh.prototype.getClassName = function () {
  46374. return "GroundMesh";
  46375. };
  46376. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  46377. get: function () {
  46378. return Math.min(this._subdivisionsX, this._subdivisionsY);
  46379. },
  46380. enumerable: true,
  46381. configurable: true
  46382. });
  46383. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  46384. get: function () {
  46385. return this._subdivisionsX;
  46386. },
  46387. enumerable: true,
  46388. configurable: true
  46389. });
  46390. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  46391. get: function () {
  46392. return this._subdivisionsY;
  46393. },
  46394. enumerable: true,
  46395. configurable: true
  46396. });
  46397. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  46398. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  46399. this._subdivisionsX = chunksCount;
  46400. this._subdivisionsY = chunksCount;
  46401. this.subdivide(chunksCount);
  46402. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  46403. };
  46404. /**
  46405. * Returns a height (y) value in the Worl system :
  46406. * the ground altitude at the coordinates (x, z) expressed in the World system.
  46407. * Returns the ground y position if (x, z) are outside the ground surface.
  46408. */
  46409. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  46410. var world = this.getWorldMatrix();
  46411. var invMat = BABYLON.Tmp.Matrix[5];
  46412. world.invertToRef(invMat);
  46413. var tmpVect = BABYLON.Tmp.Vector3[8];
  46414. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  46415. x = tmpVect.x;
  46416. z = tmpVect.z;
  46417. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  46418. return this.position.y;
  46419. }
  46420. if (!this._heightQuads || this._heightQuads.length == 0) {
  46421. this._initHeightQuads();
  46422. this._computeHeightQuads();
  46423. }
  46424. var facet = this._getFacetAt(x, z);
  46425. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  46426. // return y in the World system
  46427. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  46428. return tmpVect.y;
  46429. };
  46430. /**
  46431. * Returns a normalized vector (Vector3) orthogonal to the ground
  46432. * at the ground coordinates (x, z) expressed in the World system.
  46433. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  46434. */
  46435. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  46436. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  46437. this.getNormalAtCoordinatesToRef(x, z, normal);
  46438. return normal;
  46439. };
  46440. /**
  46441. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  46442. * at the ground coordinates (x, z) expressed in the World system.
  46443. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  46444. * Returns the GroundMesh.
  46445. */
  46446. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  46447. var world = this.getWorldMatrix();
  46448. var tmpMat = BABYLON.Tmp.Matrix[5];
  46449. world.invertToRef(tmpMat);
  46450. var tmpVect = BABYLON.Tmp.Vector3[8];
  46451. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  46452. x = tmpVect.x;
  46453. z = tmpVect.z;
  46454. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  46455. return this;
  46456. }
  46457. if (!this._heightQuads || this._heightQuads.length == 0) {
  46458. this._initHeightQuads();
  46459. this._computeHeightQuads();
  46460. }
  46461. var facet = this._getFacetAt(x, z);
  46462. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  46463. return this;
  46464. };
  46465. /**
  46466. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  46467. * if the ground has been updated.
  46468. * This can be used in the render loop.
  46469. * Returns the GroundMesh.
  46470. */
  46471. GroundMesh.prototype.updateCoordinateHeights = function () {
  46472. if (!this._heightQuads || this._heightQuads.length == 0) {
  46473. this._initHeightQuads();
  46474. }
  46475. this._computeHeightQuads();
  46476. return this;
  46477. };
  46478. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  46479. GroundMesh.prototype._getFacetAt = function (x, z) {
  46480. // retrieve col and row from x, z coordinates in the ground local system
  46481. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  46482. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  46483. var quad = this._heightQuads[row * this._subdivisionsX + col];
  46484. var facet;
  46485. if (z < quad.slope.x * x + quad.slope.y) {
  46486. facet = quad.facet1;
  46487. }
  46488. else {
  46489. facet = quad.facet2;
  46490. }
  46491. return facet;
  46492. };
  46493. // Creates and populates the heightMap array with "facet" elements :
  46494. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  46495. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  46496. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  46497. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  46498. // Returns the GroundMesh.
  46499. GroundMesh.prototype._initHeightQuads = function () {
  46500. var subdivisionsX = this._subdivisionsX;
  46501. var subdivisionsY = this._subdivisionsY;
  46502. this._heightQuads = new Array();
  46503. for (var row = 0; row < subdivisionsY; row++) {
  46504. for (var col = 0; col < subdivisionsX; col++) {
  46505. 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) };
  46506. this._heightQuads[row * subdivisionsX + col] = quad;
  46507. }
  46508. }
  46509. return this;
  46510. };
  46511. // Compute each quad element values and update the the heightMap array :
  46512. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  46513. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  46514. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  46515. // Returns the GroundMesh.
  46516. GroundMesh.prototype._computeHeightQuads = function () {
  46517. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46518. if (!positions) {
  46519. return this;
  46520. }
  46521. var v1 = BABYLON.Tmp.Vector3[3];
  46522. var v2 = BABYLON.Tmp.Vector3[2];
  46523. var v3 = BABYLON.Tmp.Vector3[1];
  46524. var v4 = BABYLON.Tmp.Vector3[0];
  46525. var v1v2 = BABYLON.Tmp.Vector3[4];
  46526. var v1v3 = BABYLON.Tmp.Vector3[5];
  46527. var v1v4 = BABYLON.Tmp.Vector3[6];
  46528. var norm1 = BABYLON.Tmp.Vector3[7];
  46529. var norm2 = BABYLON.Tmp.Vector3[8];
  46530. var i = 0;
  46531. var j = 0;
  46532. var k = 0;
  46533. var cd = 0; // 2D slope coefficient : z = cd * x + h
  46534. var h = 0;
  46535. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  46536. var d2 = 0;
  46537. var subdivisionsX = this._subdivisionsX;
  46538. var subdivisionsY = this._subdivisionsY;
  46539. for (var row = 0; row < subdivisionsY; row++) {
  46540. for (var col = 0; col < subdivisionsX; col++) {
  46541. i = col * 3;
  46542. j = row * (subdivisionsX + 1) * 3;
  46543. k = (row + 1) * (subdivisionsX + 1) * 3;
  46544. v1.x = positions[j + i];
  46545. v1.y = positions[j + i + 1];
  46546. v1.z = positions[j + i + 2];
  46547. v2.x = positions[j + i + 3];
  46548. v2.y = positions[j + i + 4];
  46549. v2.z = positions[j + i + 5];
  46550. v3.x = positions[k + i];
  46551. v3.y = positions[k + i + 1];
  46552. v3.z = positions[k + i + 2];
  46553. v4.x = positions[k + i + 3];
  46554. v4.y = positions[k + i + 4];
  46555. v4.z = positions[k + i + 5];
  46556. // 2D slope V1V4
  46557. cd = (v4.z - v1.z) / (v4.x - v1.x);
  46558. h = v1.z - cd * v1.x; // v1 belongs to the slope
  46559. // facet equations :
  46560. // we compute each facet normal vector
  46561. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  46562. // we compute the value d by applying the equation to v1 which belongs to the plane
  46563. // then we store the facet equation in a Vector4
  46564. v2.subtractToRef(v1, v1v2);
  46565. v3.subtractToRef(v1, v1v3);
  46566. v4.subtractToRef(v1, v1v4);
  46567. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  46568. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  46569. norm1.normalize();
  46570. norm2.normalize();
  46571. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  46572. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  46573. var quad = this._heightQuads[row * subdivisionsX + col];
  46574. quad.slope.copyFromFloats(cd, h);
  46575. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  46576. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  46577. }
  46578. }
  46579. return this;
  46580. };
  46581. GroundMesh.prototype.serialize = function (serializationObject) {
  46582. _super.prototype.serialize.call(this, serializationObject);
  46583. serializationObject.subdivisionsX = this._subdivisionsX;
  46584. serializationObject.subdivisionsY = this._subdivisionsY;
  46585. serializationObject.minX = this._minX;
  46586. serializationObject.maxX = this._maxX;
  46587. serializationObject.minZ = this._minZ;
  46588. serializationObject.maxZ = this._maxZ;
  46589. serializationObject.width = this._width;
  46590. serializationObject.height = this._height;
  46591. };
  46592. GroundMesh.Parse = function (parsedMesh, scene) {
  46593. var result = new GroundMesh(parsedMesh.name, scene);
  46594. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  46595. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  46596. result._minX = parsedMesh.minX;
  46597. result._maxX = parsedMesh.maxX;
  46598. result._minZ = parsedMesh.minZ;
  46599. result._maxZ = parsedMesh.maxZ;
  46600. result._width = parsedMesh.width;
  46601. result._height = parsedMesh.height;
  46602. return result;
  46603. };
  46604. return GroundMesh;
  46605. }(BABYLON.Mesh));
  46606. BABYLON.GroundMesh = GroundMesh;
  46607. })(BABYLON || (BABYLON = {}));
  46608. //# sourceMappingURL=babylon.groundMesh.js.map
  46609. var BABYLON;
  46610. (function (BABYLON) {
  46611. /**
  46612. * Creates an instance based on a source mesh.
  46613. */
  46614. var InstancedMesh = /** @class */ (function (_super) {
  46615. __extends(InstancedMesh, _super);
  46616. function InstancedMesh(name, source) {
  46617. var _this = _super.call(this, name, source.getScene()) || this;
  46618. source.instances.push(_this);
  46619. _this._sourceMesh = source;
  46620. _this.position.copyFrom(source.position);
  46621. _this.rotation.copyFrom(source.rotation);
  46622. _this.scaling.copyFrom(source.scaling);
  46623. if (source.rotationQuaternion) {
  46624. _this.rotationQuaternion = source.rotationQuaternion.clone();
  46625. }
  46626. _this.infiniteDistance = source.infiniteDistance;
  46627. _this.setPivotMatrix(source.getPivotMatrix());
  46628. _this.refreshBoundingInfo();
  46629. _this._syncSubMeshes();
  46630. return _this;
  46631. }
  46632. /**
  46633. * Returns the string "InstancedMesh".
  46634. */
  46635. InstancedMesh.prototype.getClassName = function () {
  46636. return "InstancedMesh";
  46637. };
  46638. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  46639. // Methods
  46640. get: function () {
  46641. return this._sourceMesh.receiveShadows;
  46642. },
  46643. enumerable: true,
  46644. configurable: true
  46645. });
  46646. Object.defineProperty(InstancedMesh.prototype, "material", {
  46647. get: function () {
  46648. return this._sourceMesh.material;
  46649. },
  46650. enumerable: true,
  46651. configurable: true
  46652. });
  46653. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  46654. get: function () {
  46655. return this._sourceMesh.visibility;
  46656. },
  46657. enumerable: true,
  46658. configurable: true
  46659. });
  46660. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  46661. get: function () {
  46662. return this._sourceMesh.skeleton;
  46663. },
  46664. enumerable: true,
  46665. configurable: true
  46666. });
  46667. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  46668. get: function () {
  46669. return this._sourceMesh.renderingGroupId;
  46670. },
  46671. enumerable: true,
  46672. configurable: true
  46673. });
  46674. /**
  46675. * Returns the total number of vertices (integer).
  46676. */
  46677. InstancedMesh.prototype.getTotalVertices = function () {
  46678. return this._sourceMesh.getTotalVertices();
  46679. };
  46680. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  46681. get: function () {
  46682. return this._sourceMesh;
  46683. },
  46684. enumerable: true,
  46685. configurable: true
  46686. });
  46687. /**
  46688. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  46689. */
  46690. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  46691. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  46692. };
  46693. /**
  46694. * Sets the vertex data of the mesh geometry for the requested `kind`.
  46695. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  46696. * The `data` are either a numeric array either a Float32Array.
  46697. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  46698. * 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).
  46699. * Note that a new underlying VertexBuffer object is created each call.
  46700. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  46701. *
  46702. * Possible `kind` values :
  46703. * - BABYLON.VertexBuffer.PositionKind
  46704. * - BABYLON.VertexBuffer.UVKind
  46705. * - BABYLON.VertexBuffer.UV2Kind
  46706. * - BABYLON.VertexBuffer.UV3Kind
  46707. * - BABYLON.VertexBuffer.UV4Kind
  46708. * - BABYLON.VertexBuffer.UV5Kind
  46709. * - BABYLON.VertexBuffer.UV6Kind
  46710. * - BABYLON.VertexBuffer.ColorKind
  46711. * - BABYLON.VertexBuffer.MatricesIndicesKind
  46712. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  46713. * - BABYLON.VertexBuffer.MatricesWeightsKind
  46714. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  46715. *
  46716. * Returns the Mesh.
  46717. */
  46718. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  46719. if (this.sourceMesh) {
  46720. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  46721. }
  46722. return this.sourceMesh;
  46723. };
  46724. /**
  46725. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  46726. * If the mesh has no geometry, it is simply returned as it is.
  46727. * The `data` are either a numeric array either a Float32Array.
  46728. * No new underlying VertexBuffer object is created.
  46729. * 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.
  46730. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  46731. *
  46732. * Possible `kind` values :
  46733. * - BABYLON.VertexBuffer.PositionKind
  46734. * - BABYLON.VertexBuffer.UVKind
  46735. * - BABYLON.VertexBuffer.UV2Kind
  46736. * - BABYLON.VertexBuffer.UV3Kind
  46737. * - BABYLON.VertexBuffer.UV4Kind
  46738. * - BABYLON.VertexBuffer.UV5Kind
  46739. * - BABYLON.VertexBuffer.UV6Kind
  46740. * - BABYLON.VertexBuffer.ColorKind
  46741. * - BABYLON.VertexBuffer.MatricesIndicesKind
  46742. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  46743. * - BABYLON.VertexBuffer.MatricesWeightsKind
  46744. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  46745. *
  46746. * Returns the Mesh.
  46747. */
  46748. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  46749. if (this.sourceMesh) {
  46750. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  46751. }
  46752. return this.sourceMesh;
  46753. };
  46754. /**
  46755. * Sets the mesh indices.
  46756. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  46757. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  46758. * This method creates a new index buffer each call.
  46759. * Returns the Mesh.
  46760. */
  46761. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  46762. if (totalVertices === void 0) { totalVertices = null; }
  46763. if (this.sourceMesh) {
  46764. this.sourceMesh.setIndices(indices, totalVertices);
  46765. }
  46766. return this.sourceMesh;
  46767. };
  46768. /**
  46769. * Boolean : True if the mesh owns the requested kind of data.
  46770. */
  46771. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  46772. return this._sourceMesh.isVerticesDataPresent(kind);
  46773. };
  46774. /**
  46775. * Returns an array of indices (IndicesArray).
  46776. */
  46777. InstancedMesh.prototype.getIndices = function () {
  46778. return this._sourceMesh.getIndices();
  46779. };
  46780. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  46781. get: function () {
  46782. return this._sourceMesh._positions;
  46783. },
  46784. enumerable: true,
  46785. configurable: true
  46786. });
  46787. /**
  46788. * Sets a new updated BoundingInfo to the mesh.
  46789. * Returns the mesh.
  46790. */
  46791. InstancedMesh.prototype.refreshBoundingInfo = function () {
  46792. var meshBB = this._sourceMesh.getBoundingInfo();
  46793. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  46794. this._updateBoundingInfo();
  46795. return this;
  46796. };
  46797. InstancedMesh.prototype._preActivate = function () {
  46798. if (this._currentLOD) {
  46799. this._currentLOD._preActivate();
  46800. }
  46801. return this;
  46802. };
  46803. InstancedMesh.prototype._activate = function (renderId) {
  46804. if (this._currentLOD) {
  46805. this._currentLOD._registerInstanceForRenderId(this, renderId);
  46806. }
  46807. return this;
  46808. };
  46809. /**
  46810. * Returns the current associated LOD AbstractMesh.
  46811. */
  46812. InstancedMesh.prototype.getLOD = function (camera) {
  46813. if (!camera) {
  46814. return this;
  46815. }
  46816. var boundingInfo = this.getBoundingInfo();
  46817. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  46818. if (this._currentLOD === this.sourceMesh) {
  46819. return this;
  46820. }
  46821. return this._currentLOD;
  46822. };
  46823. InstancedMesh.prototype._syncSubMeshes = function () {
  46824. this.releaseSubMeshes();
  46825. if (this._sourceMesh.subMeshes) {
  46826. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  46827. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  46828. }
  46829. }
  46830. return this;
  46831. };
  46832. InstancedMesh.prototype._generatePointsArray = function () {
  46833. return this._sourceMesh._generatePointsArray();
  46834. };
  46835. /**
  46836. * Creates a new InstancedMesh from the current mesh.
  46837. * - name (string) : the cloned mesh name
  46838. * - newParent (optional Node) : the optional Node to parent the clone to.
  46839. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  46840. *
  46841. * Returns the clone.
  46842. */
  46843. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  46844. var result = this._sourceMesh.createInstance(name);
  46845. // Deep copy
  46846. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  46847. // Bounding info
  46848. this.refreshBoundingInfo();
  46849. // Parent
  46850. if (newParent) {
  46851. result.parent = newParent;
  46852. }
  46853. if (!doNotCloneChildren) {
  46854. // Children
  46855. for (var index = 0; index < this.getScene().meshes.length; index++) {
  46856. var mesh = this.getScene().meshes[index];
  46857. if (mesh.parent === this) {
  46858. mesh.clone(mesh.name, result);
  46859. }
  46860. }
  46861. }
  46862. result.computeWorldMatrix(true);
  46863. return result;
  46864. };
  46865. /**
  46866. * Disposes the InstancedMesh.
  46867. * Returns nothing.
  46868. */
  46869. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  46870. // Remove from mesh
  46871. var index = this._sourceMesh.instances.indexOf(this);
  46872. this._sourceMesh.instances.splice(index, 1);
  46873. _super.prototype.dispose.call(this, doNotRecurse);
  46874. };
  46875. return InstancedMesh;
  46876. }(BABYLON.AbstractMesh));
  46877. BABYLON.InstancedMesh = InstancedMesh;
  46878. })(BABYLON || (BABYLON = {}));
  46879. //# sourceMappingURL=babylon.instancedMesh.js.map
  46880. var BABYLON;
  46881. (function (BABYLON) {
  46882. var LinesMesh = /** @class */ (function (_super) {
  46883. __extends(LinesMesh, _super);
  46884. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  46885. if (scene === void 0) { scene = null; }
  46886. if (parent === void 0) { parent = null; }
  46887. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  46888. _this.useVertexColor = useVertexColor;
  46889. _this.useVertexAlpha = useVertexAlpha;
  46890. _this.color = new BABYLON.Color3(1, 1, 1);
  46891. _this.alpha = 1;
  46892. if (source) {
  46893. _this.color = source.color.clone();
  46894. _this.alpha = source.alpha;
  46895. _this.useVertexColor = source.useVertexColor;
  46896. _this.useVertexAlpha = source.useVertexAlpha;
  46897. }
  46898. _this._intersectionThreshold = 0.1;
  46899. var defines = [];
  46900. var options = {
  46901. attributes: [BABYLON.VertexBuffer.PositionKind],
  46902. uniforms: ["world", "viewProjection"],
  46903. needAlphaBlending: false,
  46904. defines: defines
  46905. };
  46906. if (!useVertexColor) {
  46907. options.uniforms.push("color");
  46908. }
  46909. else {
  46910. options.needAlphaBlending = (useVertexAlpha) ? true : false;
  46911. options.defines.push("#define VERTEXCOLOR");
  46912. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  46913. }
  46914. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  46915. return _this;
  46916. }
  46917. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  46918. /**
  46919. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  46920. * This margin is expressed in world space coordinates, so its value may vary.
  46921. * Default value is 0.1
  46922. * @returns the intersection Threshold value.
  46923. */
  46924. get: function () {
  46925. return this._intersectionThreshold;
  46926. },
  46927. /**
  46928. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  46929. * This margin is expressed in world space coordinates, so its value may vary.
  46930. * @param value the new threshold to apply
  46931. */
  46932. set: function (value) {
  46933. if (this._intersectionThreshold === value) {
  46934. return;
  46935. }
  46936. this._intersectionThreshold = value;
  46937. if (this.geometry) {
  46938. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  46939. }
  46940. },
  46941. enumerable: true,
  46942. configurable: true
  46943. });
  46944. /**
  46945. * Returns the string "LineMesh"
  46946. */
  46947. LinesMesh.prototype.getClassName = function () {
  46948. return "LinesMesh";
  46949. };
  46950. Object.defineProperty(LinesMesh.prototype, "material", {
  46951. get: function () {
  46952. return this._colorShader;
  46953. },
  46954. set: function (value) {
  46955. // Do nothing
  46956. },
  46957. enumerable: true,
  46958. configurable: true
  46959. });
  46960. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  46961. get: function () {
  46962. return false;
  46963. },
  46964. enumerable: true,
  46965. configurable: true
  46966. });
  46967. LinesMesh.prototype.createInstance = function (name) {
  46968. throw new Error("LinesMeshes do not support createInstance.");
  46969. };
  46970. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  46971. if (!this._geometry) {
  46972. return this;
  46973. }
  46974. // VBOs
  46975. this._geometry._bind(this._colorShader.getEffect());
  46976. // Color
  46977. if (!this.useVertexColor) {
  46978. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  46979. }
  46980. return this;
  46981. };
  46982. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  46983. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  46984. return this;
  46985. }
  46986. var engine = this.getScene().getEngine();
  46987. // Draw order
  46988. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  46989. return this;
  46990. };
  46991. LinesMesh.prototype.dispose = function (doNotRecurse) {
  46992. this._colorShader.dispose();
  46993. _super.prototype.dispose.call(this, doNotRecurse);
  46994. };
  46995. /**
  46996. * Returns a new LineMesh object cloned from the current one.
  46997. */
  46998. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  46999. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  47000. };
  47001. return LinesMesh;
  47002. }(BABYLON.Mesh));
  47003. BABYLON.LinesMesh = LinesMesh;
  47004. })(BABYLON || (BABYLON = {}));
  47005. //# sourceMappingURL=babylon.linesMesh.js.map
  47006. var BABYLON;
  47007. (function (BABYLON) {
  47008. var ShaderMaterial = /** @class */ (function (_super) {
  47009. __extends(ShaderMaterial, _super);
  47010. function ShaderMaterial(name, scene, shaderPath, options) {
  47011. var _this = _super.call(this, name, scene) || this;
  47012. _this._textures = {};
  47013. _this._textureArrays = {};
  47014. _this._floats = {};
  47015. _this._floatsArrays = {};
  47016. _this._colors3 = {};
  47017. _this._colors3Arrays = {};
  47018. _this._colors4 = {};
  47019. _this._vectors2 = {};
  47020. _this._vectors3 = {};
  47021. _this._vectors4 = {};
  47022. _this._matrices = {};
  47023. _this._matrices3x3 = {};
  47024. _this._matrices2x2 = {};
  47025. _this._vectors3Arrays = {};
  47026. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  47027. _this._shaderPath = shaderPath;
  47028. options.needAlphaBlending = options.needAlphaBlending || false;
  47029. options.needAlphaTesting = options.needAlphaTesting || false;
  47030. options.attributes = options.attributes || ["position", "normal", "uv"];
  47031. options.uniforms = options.uniforms || ["worldViewProjection"];
  47032. options.uniformBuffers = options.uniformBuffers || [];
  47033. options.samplers = options.samplers || [];
  47034. options.defines = options.defines || [];
  47035. _this._options = options;
  47036. return _this;
  47037. }
  47038. ShaderMaterial.prototype.getClassName = function () {
  47039. return "ShaderMaterial";
  47040. };
  47041. ShaderMaterial.prototype.needAlphaBlending = function () {
  47042. return this._options.needAlphaBlending;
  47043. };
  47044. ShaderMaterial.prototype.needAlphaTesting = function () {
  47045. return this._options.needAlphaTesting;
  47046. };
  47047. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  47048. if (this._options.uniforms.indexOf(uniformName) === -1) {
  47049. this._options.uniforms.push(uniformName);
  47050. }
  47051. };
  47052. ShaderMaterial.prototype.setTexture = function (name, texture) {
  47053. if (this._options.samplers.indexOf(name) === -1) {
  47054. this._options.samplers.push(name);
  47055. }
  47056. this._textures[name] = texture;
  47057. return this;
  47058. };
  47059. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  47060. if (this._options.samplers.indexOf(name) === -1) {
  47061. this._options.samplers.push(name);
  47062. }
  47063. this._checkUniform(name);
  47064. this._textureArrays[name] = textures;
  47065. return this;
  47066. };
  47067. ShaderMaterial.prototype.setFloat = function (name, value) {
  47068. this._checkUniform(name);
  47069. this._floats[name] = value;
  47070. return this;
  47071. };
  47072. ShaderMaterial.prototype.setFloats = function (name, value) {
  47073. this._checkUniform(name);
  47074. this._floatsArrays[name] = value;
  47075. return this;
  47076. };
  47077. ShaderMaterial.prototype.setColor3 = function (name, value) {
  47078. this._checkUniform(name);
  47079. this._colors3[name] = value;
  47080. return this;
  47081. };
  47082. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  47083. this._checkUniform(name);
  47084. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  47085. color.toArray(arr, arr.length);
  47086. return arr;
  47087. }, []);
  47088. return this;
  47089. };
  47090. ShaderMaterial.prototype.setColor4 = function (name, value) {
  47091. this._checkUniform(name);
  47092. this._colors4[name] = value;
  47093. return this;
  47094. };
  47095. ShaderMaterial.prototype.setVector2 = function (name, value) {
  47096. this._checkUniform(name);
  47097. this._vectors2[name] = value;
  47098. return this;
  47099. };
  47100. ShaderMaterial.prototype.setVector3 = function (name, value) {
  47101. this._checkUniform(name);
  47102. this._vectors3[name] = value;
  47103. return this;
  47104. };
  47105. ShaderMaterial.prototype.setVector4 = function (name, value) {
  47106. this._checkUniform(name);
  47107. this._vectors4[name] = value;
  47108. return this;
  47109. };
  47110. ShaderMaterial.prototype.setMatrix = function (name, value) {
  47111. this._checkUniform(name);
  47112. this._matrices[name] = value;
  47113. return this;
  47114. };
  47115. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  47116. this._checkUniform(name);
  47117. this._matrices3x3[name] = value;
  47118. return this;
  47119. };
  47120. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  47121. this._checkUniform(name);
  47122. this._matrices2x2[name] = value;
  47123. return this;
  47124. };
  47125. ShaderMaterial.prototype.setArray3 = function (name, value) {
  47126. this._checkUniform(name);
  47127. this._vectors3Arrays[name] = value;
  47128. return this;
  47129. };
  47130. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  47131. if (!mesh) {
  47132. return true;
  47133. }
  47134. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  47135. return false;
  47136. }
  47137. return false;
  47138. };
  47139. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  47140. var scene = this.getScene();
  47141. var engine = scene.getEngine();
  47142. if (!this.checkReadyOnEveryCall) {
  47143. if (this._renderId === scene.getRenderId()) {
  47144. if (this._checkCache(scene, mesh, useInstances)) {
  47145. return true;
  47146. }
  47147. }
  47148. }
  47149. // Instances
  47150. var defines = [];
  47151. var attribs = [];
  47152. var fallbacks = new BABYLON.EffectFallbacks();
  47153. if (useInstances) {
  47154. defines.push("#define INSTANCES");
  47155. }
  47156. for (var index = 0; index < this._options.defines.length; index++) {
  47157. defines.push(this._options.defines[index]);
  47158. }
  47159. for (var index = 0; index < this._options.attributes.length; index++) {
  47160. attribs.push(this._options.attributes[index]);
  47161. }
  47162. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  47163. attribs.push(BABYLON.VertexBuffer.ColorKind);
  47164. defines.push("#define VERTEXCOLOR");
  47165. }
  47166. // Bones
  47167. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  47168. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47169. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47170. if (mesh.numBoneInfluencers > 4) {
  47171. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  47172. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  47173. }
  47174. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47175. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47176. fallbacks.addCPUSkinningFallback(0, mesh);
  47177. if (this._options.uniforms.indexOf("mBones") === -1) {
  47178. this._options.uniforms.push("mBones");
  47179. }
  47180. }
  47181. else {
  47182. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47183. }
  47184. // Textures
  47185. for (var name in this._textures) {
  47186. if (!this._textures[name].isReady()) {
  47187. return false;
  47188. }
  47189. }
  47190. // Alpha test
  47191. if (engine.getAlphaTesting()) {
  47192. defines.push("#define ALPHATEST");
  47193. }
  47194. var previousEffect = this._effect;
  47195. var join = defines.join("\n");
  47196. this._effect = engine.createEffect(this._shaderPath, {
  47197. attributes: attribs,
  47198. uniformsNames: this._options.uniforms,
  47199. uniformBuffersNames: this._options.uniformBuffers,
  47200. samplers: this._options.samplers,
  47201. defines: join,
  47202. fallbacks: fallbacks,
  47203. onCompiled: this.onCompiled,
  47204. onError: this.onError
  47205. }, engine);
  47206. if (!this._effect.isReady()) {
  47207. return false;
  47208. }
  47209. if (previousEffect !== this._effect) {
  47210. scene.resetCachedMaterial();
  47211. }
  47212. this._renderId = scene.getRenderId();
  47213. return true;
  47214. };
  47215. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  47216. var scene = this.getScene();
  47217. if (!this._effect) {
  47218. return;
  47219. }
  47220. if (this._options.uniforms.indexOf("world") !== -1) {
  47221. this._effect.setMatrix("world", world);
  47222. }
  47223. if (this._options.uniforms.indexOf("worldView") !== -1) {
  47224. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  47225. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  47226. }
  47227. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  47228. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  47229. }
  47230. };
  47231. ShaderMaterial.prototype.bind = function (world, mesh) {
  47232. // Std values
  47233. this.bindOnlyWorldMatrix(world);
  47234. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  47235. if (this._options.uniforms.indexOf("view") !== -1) {
  47236. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  47237. }
  47238. if (this._options.uniforms.indexOf("projection") !== -1) {
  47239. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  47240. }
  47241. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  47242. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  47243. }
  47244. // Bones
  47245. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  47246. var name;
  47247. // Texture
  47248. for (name in this._textures) {
  47249. this._effect.setTexture(name, this._textures[name]);
  47250. }
  47251. // Texture arrays
  47252. for (name in this._textureArrays) {
  47253. this._effect.setTextureArray(name, this._textureArrays[name]);
  47254. }
  47255. // Float
  47256. for (name in this._floats) {
  47257. this._effect.setFloat(name, this._floats[name]);
  47258. }
  47259. // Float s
  47260. for (name in this._floatsArrays) {
  47261. this._effect.setArray(name, this._floatsArrays[name]);
  47262. }
  47263. // Color3
  47264. for (name in this._colors3) {
  47265. this._effect.setColor3(name, this._colors3[name]);
  47266. }
  47267. for (name in this._colors3Arrays) {
  47268. this._effect.setArray3(name, this._colors3Arrays[name]);
  47269. }
  47270. // Color4
  47271. for (name in this._colors4) {
  47272. var color = this._colors4[name];
  47273. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  47274. }
  47275. // Vector2
  47276. for (name in this._vectors2) {
  47277. this._effect.setVector2(name, this._vectors2[name]);
  47278. }
  47279. // Vector3
  47280. for (name in this._vectors3) {
  47281. this._effect.setVector3(name, this._vectors3[name]);
  47282. }
  47283. // Vector4
  47284. for (name in this._vectors4) {
  47285. this._effect.setVector4(name, this._vectors4[name]);
  47286. }
  47287. // Matrix
  47288. for (name in this._matrices) {
  47289. this._effect.setMatrix(name, this._matrices[name]);
  47290. }
  47291. // Matrix 3x3
  47292. for (name in this._matrices3x3) {
  47293. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  47294. }
  47295. // Matrix 2x2
  47296. for (name in this._matrices2x2) {
  47297. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  47298. }
  47299. // Vector3Array
  47300. for (name in this._vectors3Arrays) {
  47301. this._effect.setArray3(name, this._vectors3Arrays[name]);
  47302. }
  47303. }
  47304. this._afterBind(mesh);
  47305. };
  47306. ShaderMaterial.prototype.getActiveTextures = function () {
  47307. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47308. for (var name in this._textures) {
  47309. activeTextures.push(this._textures[name]);
  47310. }
  47311. for (var name in this._textureArrays) {
  47312. var array = this._textureArrays[name];
  47313. for (var index = 0; index < array.length; index++) {
  47314. activeTextures.push(array[index]);
  47315. }
  47316. }
  47317. return activeTextures;
  47318. };
  47319. ShaderMaterial.prototype.hasTexture = function (texture) {
  47320. if (_super.prototype.hasTexture.call(this, texture)) {
  47321. return true;
  47322. }
  47323. for (var name in this._textures) {
  47324. if (this._textures[name] === texture) {
  47325. return true;
  47326. }
  47327. }
  47328. for (var name in this._textureArrays) {
  47329. var array = this._textureArrays[name];
  47330. for (var index = 0; index < array.length; index++) {
  47331. if (array[index] === texture) {
  47332. return true;
  47333. }
  47334. }
  47335. }
  47336. return false;
  47337. };
  47338. ShaderMaterial.prototype.clone = function (name) {
  47339. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  47340. return newShaderMaterial;
  47341. };
  47342. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  47343. if (forceDisposeTextures) {
  47344. var name;
  47345. for (name in this._textures) {
  47346. this._textures[name].dispose();
  47347. }
  47348. for (name in this._textureArrays) {
  47349. var array = this._textureArrays[name];
  47350. for (var index = 0; index < array.length; index++) {
  47351. array[index].dispose();
  47352. }
  47353. }
  47354. }
  47355. this._textures = {};
  47356. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  47357. };
  47358. ShaderMaterial.prototype.serialize = function () {
  47359. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47360. serializationObject.customType = "BABYLON.ShaderMaterial";
  47361. serializationObject.options = this._options;
  47362. serializationObject.shaderPath = this._shaderPath;
  47363. var name;
  47364. // Texture
  47365. serializationObject.textures = {};
  47366. for (name in this._textures) {
  47367. serializationObject.textures[name] = this._textures[name].serialize();
  47368. }
  47369. // Texture arrays
  47370. serializationObject.textureArrays = {};
  47371. for (name in this._textureArrays) {
  47372. serializationObject.textureArrays[name] = [];
  47373. var array = this._textureArrays[name];
  47374. for (var index = 0; index < array.length; index++) {
  47375. serializationObject.textureArrays[name].push(array[index].serialize());
  47376. }
  47377. }
  47378. // Float
  47379. serializationObject.floats = {};
  47380. for (name in this._floats) {
  47381. serializationObject.floats[name] = this._floats[name];
  47382. }
  47383. // Float s
  47384. serializationObject.FloatArrays = {};
  47385. for (name in this._floatsArrays) {
  47386. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  47387. }
  47388. // Color3
  47389. serializationObject.colors3 = {};
  47390. for (name in this._colors3) {
  47391. serializationObject.colors3[name] = this._colors3[name].asArray();
  47392. }
  47393. // Color3 array
  47394. serializationObject.colors3Arrays = {};
  47395. for (name in this._colors3Arrays) {
  47396. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  47397. }
  47398. // Color4
  47399. serializationObject.colors4 = {};
  47400. for (name in this._colors4) {
  47401. serializationObject.colors4[name] = this._colors4[name].asArray();
  47402. }
  47403. // Vector2
  47404. serializationObject.vectors2 = {};
  47405. for (name in this._vectors2) {
  47406. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  47407. }
  47408. // Vector3
  47409. serializationObject.vectors3 = {};
  47410. for (name in this._vectors3) {
  47411. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  47412. }
  47413. // Vector4
  47414. serializationObject.vectors4 = {};
  47415. for (name in this._vectors4) {
  47416. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  47417. }
  47418. // Matrix
  47419. serializationObject.matrices = {};
  47420. for (name in this._matrices) {
  47421. serializationObject.matrices[name] = this._matrices[name].asArray();
  47422. }
  47423. // Matrix 3x3
  47424. serializationObject.matrices3x3 = {};
  47425. for (name in this._matrices3x3) {
  47426. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  47427. }
  47428. // Matrix 2x2
  47429. serializationObject.matrices2x2 = {};
  47430. for (name in this._matrices2x2) {
  47431. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  47432. }
  47433. // Vector3Array
  47434. serializationObject.vectors3Arrays = {};
  47435. for (name in this._vectors3Arrays) {
  47436. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  47437. }
  47438. return serializationObject;
  47439. };
  47440. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  47441. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  47442. var name;
  47443. // Texture
  47444. for (name in source.textures) {
  47445. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  47446. }
  47447. // Texture arrays
  47448. for (name in source.textureArrays) {
  47449. var array = source.textureArrays[name];
  47450. var textureArray = new Array();
  47451. for (var index = 0; index < array.length; index++) {
  47452. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  47453. }
  47454. material.setTextureArray(name, textureArray);
  47455. }
  47456. // Float
  47457. for (name in source.floats) {
  47458. material.setFloat(name, source.floats[name]);
  47459. }
  47460. // Float s
  47461. for (name in source.floatsArrays) {
  47462. material.setFloats(name, source.floatsArrays[name]);
  47463. }
  47464. // Color3
  47465. for (name in source.colors3) {
  47466. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  47467. }
  47468. // Color3 arrays
  47469. for (name in source.colors3Arrays) {
  47470. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  47471. if (i % 3 === 0) {
  47472. arr.push([num]);
  47473. }
  47474. else {
  47475. arr[arr.length - 1].push(num);
  47476. }
  47477. return arr;
  47478. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  47479. material.setColor3Array(name, colors);
  47480. }
  47481. // Color4
  47482. for (name in source.colors4) {
  47483. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  47484. }
  47485. // Vector2
  47486. for (name in source.vectors2) {
  47487. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  47488. }
  47489. // Vector3
  47490. for (name in source.vectors3) {
  47491. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  47492. }
  47493. // Vector4
  47494. for (name in source.vectors4) {
  47495. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  47496. }
  47497. // Matrix
  47498. for (name in source.matrices) {
  47499. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  47500. }
  47501. // Matrix 3x3
  47502. for (name in source.matrices3x3) {
  47503. material.setMatrix3x3(name, source.matrices3x3[name]);
  47504. }
  47505. // Matrix 2x2
  47506. for (name in source.matrices2x2) {
  47507. material.setMatrix2x2(name, source.matrices2x2[name]);
  47508. }
  47509. // Vector3Array
  47510. for (name in source.vectors3Arrays) {
  47511. material.setArray3(name, source.vectors3Arrays[name]);
  47512. }
  47513. return material;
  47514. };
  47515. return ShaderMaterial;
  47516. }(BABYLON.Material));
  47517. BABYLON.ShaderMaterial = ShaderMaterial;
  47518. })(BABYLON || (BABYLON = {}));
  47519. //# sourceMappingURL=babylon.shaderMaterial.js.map
  47520. var BABYLON;
  47521. (function (BABYLON) {
  47522. var MeshBuilder = /** @class */ (function () {
  47523. function MeshBuilder() {
  47524. }
  47525. MeshBuilder.updateSideOrientation = function (orientation) {
  47526. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  47527. return BABYLON.Mesh.DOUBLESIDE;
  47528. }
  47529. if (orientation === undefined || orientation === null) {
  47530. return BABYLON.Mesh.FRONTSIDE;
  47531. }
  47532. return orientation;
  47533. };
  47534. /**
  47535. * Creates a box mesh.
  47536. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  47537. * The parameter `size` sets the size (float) of each box side (default 1).
  47538. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  47539. * 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).
  47540. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  47541. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47542. * 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).
  47543. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47544. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47545. */
  47546. MeshBuilder.CreateBox = function (name, options, scene) {
  47547. if (scene === void 0) { scene = null; }
  47548. var box = new BABYLON.Mesh(name, scene);
  47549. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47550. box._originalBuilderSideOrientation = options.sideOrientation;
  47551. var vertexData = BABYLON.VertexData.CreateBox(options);
  47552. vertexData.applyToMesh(box, options.updatable);
  47553. return box;
  47554. };
  47555. /**
  47556. * Creates a sphere mesh.
  47557. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  47558. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  47559. * 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`).
  47560. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  47561. * 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
  47562. * 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).
  47563. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47564. * 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).
  47565. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47566. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47567. */
  47568. MeshBuilder.CreateSphere = function (name, options, scene) {
  47569. var sphere = new BABYLON.Mesh(name, scene);
  47570. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47571. sphere._originalBuilderSideOrientation = options.sideOrientation;
  47572. var vertexData = BABYLON.VertexData.CreateSphere(options);
  47573. vertexData.applyToMesh(sphere, options.updatable);
  47574. return sphere;
  47575. };
  47576. /**
  47577. * Creates a plane polygonal mesh. By default, this is a disc.
  47578. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  47579. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  47580. * 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.
  47581. * 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
  47582. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47583. * 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).
  47584. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47585. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47586. */
  47587. MeshBuilder.CreateDisc = function (name, options, scene) {
  47588. if (scene === void 0) { scene = null; }
  47589. var disc = new BABYLON.Mesh(name, scene);
  47590. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47591. disc._originalBuilderSideOrientation = options.sideOrientation;
  47592. var vertexData = BABYLON.VertexData.CreateDisc(options);
  47593. vertexData.applyToMesh(disc, options.updatable);
  47594. return disc;
  47595. };
  47596. /**
  47597. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  47598. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  47599. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  47600. * 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`).
  47601. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  47602. * 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.
  47603. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47604. * 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).
  47605. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47606. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47607. */
  47608. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  47609. var sphere = new BABYLON.Mesh(name, scene);
  47610. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47611. sphere._originalBuilderSideOrientation = options.sideOrientation;
  47612. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  47613. vertexData.applyToMesh(sphere, options.updatable);
  47614. return sphere;
  47615. };
  47616. ;
  47617. /**
  47618. * Creates a ribbon mesh.
  47619. * 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.
  47620. *
  47621. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  47622. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  47623. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  47624. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  47625. * 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.
  47626. * 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.
  47627. * 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
  47628. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47629. * 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).
  47630. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47631. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47632. * 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.
  47633. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  47634. * 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
  47635. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  47636. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  47637. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47638. */
  47639. MeshBuilder.CreateRibbon = function (name, options, scene) {
  47640. if (scene === void 0) { scene = null; }
  47641. var pathArray = options.pathArray;
  47642. var closeArray = options.closeArray;
  47643. var closePath = options.closePath;
  47644. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47645. var instance = options.instance;
  47646. var updatable = options.updatable;
  47647. if (instance) {
  47648. // positionFunction : ribbon case
  47649. // only pathArray and sideOrientation parameters are taken into account for positions update
  47650. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  47651. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  47652. var positionFunction = function (positions) {
  47653. var minlg = pathArray[0].length;
  47654. var i = 0;
  47655. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  47656. for (var si = 1; si <= ns; si++) {
  47657. for (var p = 0; p < pathArray.length; p++) {
  47658. var path = pathArray[p];
  47659. var l = path.length;
  47660. minlg = (minlg < l) ? minlg : l;
  47661. var j = 0;
  47662. while (j < minlg) {
  47663. positions[i] = path[j].x;
  47664. positions[i + 1] = path[j].y;
  47665. positions[i + 2] = path[j].z;
  47666. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  47667. BABYLON.Tmp.Vector3[0].x = path[j].x;
  47668. }
  47669. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  47670. BABYLON.Tmp.Vector3[1].x = path[j].x;
  47671. }
  47672. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  47673. BABYLON.Tmp.Vector3[0].y = path[j].y;
  47674. }
  47675. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  47676. BABYLON.Tmp.Vector3[1].y = path[j].y;
  47677. }
  47678. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  47679. BABYLON.Tmp.Vector3[0].z = path[j].z;
  47680. }
  47681. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  47682. BABYLON.Tmp.Vector3[1].z = path[j].z;
  47683. }
  47684. j++;
  47685. i += 3;
  47686. }
  47687. if (instance._closePath) {
  47688. positions[i] = path[0].x;
  47689. positions[i + 1] = path[0].y;
  47690. positions[i + 2] = path[0].z;
  47691. i += 3;
  47692. }
  47693. }
  47694. }
  47695. };
  47696. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47697. positionFunction(positions);
  47698. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  47699. instance._boundingInfo.update(instance._worldMatrix);
  47700. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  47701. if (options.colors) {
  47702. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47703. for (var c = 0; c < options.colors.length; c++) {
  47704. colors[c * 4] = options.colors[c].r;
  47705. colors[c * 4 + 1] = options.colors[c].g;
  47706. colors[c * 4 + 2] = options.colors[c].b;
  47707. colors[c * 4 + 3] = options.colors[c].a;
  47708. }
  47709. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  47710. }
  47711. if (options.uvs) {
  47712. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47713. for (var i = 0; i < options.uvs.length; i++) {
  47714. uvs[i * 2] = options.uvs[i].x;
  47715. uvs[i * 2 + 1] = options.uvs[i].y;
  47716. }
  47717. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  47718. }
  47719. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  47720. var indices = instance.getIndices();
  47721. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47722. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  47723. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  47724. if (instance._closePath) {
  47725. var indexFirst = 0;
  47726. var indexLast = 0;
  47727. for (var p = 0; p < pathArray.length; p++) {
  47728. indexFirst = instance._idx[p] * 3;
  47729. if (p + 1 < pathArray.length) {
  47730. indexLast = (instance._idx[p + 1] - 1) * 3;
  47731. }
  47732. else {
  47733. indexLast = normals.length - 3;
  47734. }
  47735. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  47736. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  47737. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  47738. normals[indexLast] = normals[indexFirst];
  47739. normals[indexLast + 1] = normals[indexFirst + 1];
  47740. normals[indexLast + 2] = normals[indexFirst + 2];
  47741. }
  47742. }
  47743. if (!(instance.areNormalsFrozen)) {
  47744. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  47745. }
  47746. }
  47747. return instance;
  47748. }
  47749. else {
  47750. var ribbon = new BABYLON.Mesh(name, scene);
  47751. ribbon._originalBuilderSideOrientation = sideOrientation;
  47752. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  47753. if (closePath) {
  47754. ribbon._idx = vertexData._idx;
  47755. }
  47756. ribbon._closePath = closePath;
  47757. ribbon._closeArray = closeArray;
  47758. vertexData.applyToMesh(ribbon, updatable);
  47759. return ribbon;
  47760. }
  47761. };
  47762. /**
  47763. * Creates a cylinder or a cone mesh.
  47764. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  47765. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  47766. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  47767. * 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.
  47768. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  47769. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  47770. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  47771. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  47772. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  47773. * 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).
  47774. * 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
  47775. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  47776. * 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
  47777. * 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.
  47778. * If `enclose` is false, a ring surface is one element.
  47779. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  47780. * 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
  47781. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47782. * 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).
  47783. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47784. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47785. */
  47786. MeshBuilder.CreateCylinder = function (name, options, scene) {
  47787. var cylinder = new BABYLON.Mesh(name, scene);
  47788. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47789. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  47790. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  47791. vertexData.applyToMesh(cylinder, options.updatable);
  47792. return cylinder;
  47793. };
  47794. /**
  47795. * Creates a torus mesh.
  47796. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  47797. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  47798. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  47799. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  47800. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47801. * 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).
  47802. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47803. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47804. */
  47805. MeshBuilder.CreateTorus = function (name, options, scene) {
  47806. var torus = new BABYLON.Mesh(name, scene);
  47807. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47808. torus._originalBuilderSideOrientation = options.sideOrientation;
  47809. var vertexData = BABYLON.VertexData.CreateTorus(options);
  47810. vertexData.applyToMesh(torus, options.updatable);
  47811. return torus;
  47812. };
  47813. /**
  47814. * Creates a torus knot mesh.
  47815. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  47816. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  47817. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  47818. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  47819. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  47820. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47821. * 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).
  47822. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47823. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47824. */
  47825. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  47826. var torusKnot = new BABYLON.Mesh(name, scene);
  47827. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47828. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  47829. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  47830. vertexData.applyToMesh(torusKnot, options.updatable);
  47831. return torusKnot;
  47832. };
  47833. /**
  47834. * Creates a line system mesh.
  47835. * A line system is a pool of many lines gathered in a single mesh.
  47836. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  47837. * 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.
  47838. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  47839. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  47840. * 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
  47841. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  47842. * The optional parameter `useVertexAlpha' is to be set to `true` (default `false`) when the alpha value from the former `Color4` array must be used.
  47843. * 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
  47844. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  47845. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47846. */
  47847. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  47848. var instance = options.instance;
  47849. var lines = options.lines;
  47850. var colors = options.colors;
  47851. if (instance) {
  47852. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47853. var vertexColor;
  47854. var lineColors;
  47855. if (colors) {
  47856. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47857. }
  47858. var i = 0;
  47859. var c = 0;
  47860. for (var l = 0; l < lines.length; l++) {
  47861. var points = lines[l];
  47862. for (var p = 0; p < points.length; p++) {
  47863. positions[i] = points[p].x;
  47864. positions[i + 1] = points[p].y;
  47865. positions[i + 2] = points[p].z;
  47866. if (colors && vertexColor) {
  47867. lineColors = colors[l];
  47868. vertexColor[c] = lineColors[p].r;
  47869. vertexColor[c + 1] = lineColors[p].g;
  47870. vertexColor[c + 2] = lineColors[p].b;
  47871. vertexColor[c + 3] = lineColors[p].a;
  47872. c += 4;
  47873. }
  47874. i += 3;
  47875. }
  47876. }
  47877. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  47878. if (colors && vertexColor) {
  47879. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  47880. }
  47881. return instance;
  47882. }
  47883. // line system creation
  47884. var useVertexColor = (colors) ? true : false;
  47885. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  47886. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  47887. vertexData.applyToMesh(lineSystem, options.updatable);
  47888. return lineSystem;
  47889. };
  47890. /**
  47891. * Creates a line mesh.
  47892. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  47893. * 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.
  47894. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  47895. * The parameter `points` is an array successive Vector3.
  47896. * 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
  47897. * The optional parameter `colors` is an array of successive Color4, one per line point.
  47898. * The optional parameter `useVertexAlpha' is to be set to `true` (default `false`) when the alpha value from the former `Color4` array must be used.
  47899. * When updating an instance, remember that only point positions can change, not the number of points.
  47900. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47901. */
  47902. MeshBuilder.CreateLines = function (name, options, scene) {
  47903. if (scene === void 0) { scene = null; }
  47904. var colors = (options.colors) ? [options.colors] : null;
  47905. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  47906. return lines;
  47907. };
  47908. /**
  47909. * Creates a dashed line mesh.
  47910. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  47911. * 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.
  47912. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  47913. * The parameter `points` is an array successive Vector3.
  47914. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  47915. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  47916. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  47917. * 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
  47918. * When updating an instance, remember that only point positions can change, not the number of points.
  47919. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47920. */
  47921. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  47922. if (scene === void 0) { scene = null; }
  47923. var points = options.points;
  47924. var instance = options.instance;
  47925. var gapSize = options.gapSize || 1;
  47926. var dashSize = options.dashSize || 3;
  47927. if (instance) {
  47928. var positionFunction = function (positions) {
  47929. var curvect = BABYLON.Vector3.Zero();
  47930. var nbSeg = positions.length / 6;
  47931. var lg = 0;
  47932. var nb = 0;
  47933. var shft = 0;
  47934. var dashshft = 0;
  47935. var curshft = 0;
  47936. var p = 0;
  47937. var i = 0;
  47938. var j = 0;
  47939. for (i = 0; i < points.length - 1; i++) {
  47940. points[i + 1].subtractToRef(points[i], curvect);
  47941. lg += curvect.length();
  47942. }
  47943. shft = lg / nbSeg;
  47944. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  47945. for (i = 0; i < points.length - 1; i++) {
  47946. points[i + 1].subtractToRef(points[i], curvect);
  47947. nb = Math.floor(curvect.length() / shft);
  47948. curvect.normalize();
  47949. j = 0;
  47950. while (j < nb && p < positions.length) {
  47951. curshft = shft * j;
  47952. positions[p] = points[i].x + curshft * curvect.x;
  47953. positions[p + 1] = points[i].y + curshft * curvect.y;
  47954. positions[p + 2] = points[i].z + curshft * curvect.z;
  47955. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  47956. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  47957. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  47958. p += 6;
  47959. j++;
  47960. }
  47961. }
  47962. while (p < positions.length) {
  47963. positions[p] = points[i].x;
  47964. positions[p + 1] = points[i].y;
  47965. positions[p + 2] = points[i].z;
  47966. p += 3;
  47967. }
  47968. };
  47969. instance.updateMeshPositions(positionFunction, false);
  47970. return instance;
  47971. }
  47972. // dashed lines creation
  47973. var dashedLines = new BABYLON.LinesMesh(name, scene);
  47974. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  47975. vertexData.applyToMesh(dashedLines, options.updatable);
  47976. dashedLines.dashSize = dashSize;
  47977. dashedLines.gapSize = gapSize;
  47978. return dashedLines;
  47979. };
  47980. /**
  47981. * Creates an extruded shape mesh.
  47982. * 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.
  47983. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  47984. *
  47985. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  47986. * 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
  47987. * extruded along the Z axis.
  47988. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  47989. * 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.
  47990. * The parameter `scale` (float, default 1) is the value to scale the shape.
  47991. * 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
  47992. * 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
  47993. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  47994. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47995. * 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).
  47996. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47997. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47998. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47999. */
  48000. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  48001. if (scene === void 0) { scene = null; }
  48002. var path = options.path;
  48003. var shape = options.shape;
  48004. var scale = options.scale || 1;
  48005. var rotation = options.rotation || 0;
  48006. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  48007. var updatable = options.updatable;
  48008. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48009. var instance = options.instance || null;
  48010. var invertUV = options.invertUV || false;
  48011. 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);
  48012. };
  48013. /**
  48014. * Creates an custom extruded shape mesh.
  48015. * 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.
  48016. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  48017. *
  48018. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  48019. * 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
  48020. * extruded along the Z axis.
  48021. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  48022. * 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
  48023. * and the distance of this point from the begining of the path :
  48024. * ```javascript
  48025. * var rotationFunction = function(i, distance) {
  48026. * // do things
  48027. * return rotationValue; }
  48028. * ```
  48029. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  48030. * 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
  48031. * and the distance of this point from the begining of the path :
  48032. * ```javascript
  48033. * var scaleFunction = function(i, distance) {
  48034. * // do things
  48035. * return scaleValue;}
  48036. * ```
  48037. * It must returns a float value that will be the scale value applied to the shape on each path point.
  48038. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  48039. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  48040. * 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
  48041. * 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
  48042. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  48043. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48044. * 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).
  48045. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48046. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48047. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48048. */
  48049. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  48050. var path = options.path;
  48051. var shape = options.shape;
  48052. var scaleFunction = options.scaleFunction || (function () { return 1; });
  48053. var rotationFunction = options.rotationFunction || (function () { return 0; });
  48054. var ribbonCloseArray = options.ribbonCloseArray || false;
  48055. var ribbonClosePath = options.ribbonClosePath || false;
  48056. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  48057. var updatable = options.updatable;
  48058. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48059. var instance = options.instance;
  48060. var invertUV = options.invertUV || false;
  48061. 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);
  48062. };
  48063. /**
  48064. * Creates lathe mesh.
  48065. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  48066. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  48067. *
  48068. * 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
  48069. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  48070. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  48071. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  48072. * 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.
  48073. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  48074. * 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
  48075. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48076. * 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).
  48077. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48078. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48079. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48080. */
  48081. MeshBuilder.CreateLathe = function (name, options, scene) {
  48082. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  48083. var closed = (options.closed === undefined) ? true : options.closed;
  48084. var shape = options.shape;
  48085. var radius = options.radius || 1;
  48086. var tessellation = options.tessellation || 64;
  48087. var updatable = options.updatable;
  48088. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48089. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  48090. var pi2 = Math.PI * 2;
  48091. var paths = new Array();
  48092. var invertUV = options.invertUV || false;
  48093. var i = 0;
  48094. var p = 0;
  48095. var step = pi2 / tessellation * arc;
  48096. var rotated;
  48097. var path = new Array();
  48098. ;
  48099. for (i = 0; i <= tessellation; i++) {
  48100. var path = [];
  48101. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  48102. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  48103. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  48104. }
  48105. for (p = 0; p < shape.length; p++) {
  48106. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  48107. path.push(rotated);
  48108. }
  48109. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  48110. 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));
  48111. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  48112. }
  48113. paths.push(path);
  48114. }
  48115. // lathe ribbon
  48116. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  48117. return lathe;
  48118. };
  48119. /**
  48120. * Creates a plane mesh.
  48121. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  48122. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  48123. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  48124. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  48125. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48126. * 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).
  48127. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48128. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48129. */
  48130. MeshBuilder.CreatePlane = function (name, options, scene) {
  48131. var plane = new BABYLON.Mesh(name, scene);
  48132. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48133. plane._originalBuilderSideOrientation = options.sideOrientation;
  48134. var vertexData = BABYLON.VertexData.CreatePlane(options);
  48135. vertexData.applyToMesh(plane, options.updatable);
  48136. if (options.sourcePlane) {
  48137. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  48138. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  48139. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  48140. plane.rotate(vectorProduct, product);
  48141. }
  48142. return plane;
  48143. };
  48144. /**
  48145. * Creates a ground mesh.
  48146. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  48147. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  48148. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  48149. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48150. */
  48151. MeshBuilder.CreateGround = function (name, options, scene) {
  48152. var ground = new BABYLON.GroundMesh(name, scene);
  48153. ground._setReady(false);
  48154. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  48155. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  48156. ground._width = options.width || 1;
  48157. ground._height = options.height || 1;
  48158. ground._maxX = ground._width / 2;
  48159. ground._maxZ = ground._height / 2;
  48160. ground._minX = -ground._maxX;
  48161. ground._minZ = -ground._maxZ;
  48162. var vertexData = BABYLON.VertexData.CreateGround(options);
  48163. vertexData.applyToMesh(ground, options.updatable);
  48164. ground._setReady(true);
  48165. return ground;
  48166. };
  48167. /**
  48168. * Creates a tiled ground mesh.
  48169. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  48170. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  48171. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  48172. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  48173. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  48174. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  48175. * numbers of subdivisions on the ground width and height of each tile.
  48176. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48177. */
  48178. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  48179. var tiledGround = new BABYLON.Mesh(name, scene);
  48180. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  48181. vertexData.applyToMesh(tiledGround, options.updatable);
  48182. return tiledGround;
  48183. };
  48184. /**
  48185. * Creates a ground mesh from a height map.
  48186. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  48187. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  48188. * The parameter `url` sets the URL of the height map image resource.
  48189. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  48190. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  48191. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  48192. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  48193. * 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.
  48194. * 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).
  48195. * This function is passed the newly built mesh :
  48196. * ```javascript
  48197. * function(mesh) { // do things
  48198. * return; }
  48199. * ```
  48200. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48201. */
  48202. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  48203. var width = options.width || 10.0;
  48204. var height = options.height || 10.0;
  48205. var subdivisions = options.subdivisions || 1 | 0;
  48206. var minHeight = options.minHeight || 0.0;
  48207. var maxHeight = options.maxHeight || 1.0;
  48208. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  48209. var updatable = options.updatable;
  48210. var onReady = options.onReady;
  48211. var ground = new BABYLON.GroundMesh(name, scene);
  48212. ground._subdivisionsX = subdivisions;
  48213. ground._subdivisionsY = subdivisions;
  48214. ground._width = width;
  48215. ground._height = height;
  48216. ground._maxX = ground._width / 2.0;
  48217. ground._maxZ = ground._height / 2.0;
  48218. ground._minX = -ground._maxX;
  48219. ground._minZ = -ground._maxZ;
  48220. ground._setReady(false);
  48221. var onload = function (img) {
  48222. // Getting height map data
  48223. var canvas = document.createElement("canvas");
  48224. var context = canvas.getContext("2d");
  48225. if (!context) {
  48226. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  48227. }
  48228. var bufferWidth = img.width;
  48229. var bufferHeight = img.height;
  48230. canvas.width = bufferWidth;
  48231. canvas.height = bufferHeight;
  48232. context.drawImage(img, 0, 0);
  48233. // Create VertexData from map data
  48234. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  48235. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  48236. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  48237. width: width, height: height,
  48238. subdivisions: subdivisions,
  48239. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  48240. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  48241. });
  48242. vertexData.applyToMesh(ground, updatable);
  48243. ground._setReady(true);
  48244. //execute ready callback, if set
  48245. if (onReady) {
  48246. onReady(ground);
  48247. }
  48248. };
  48249. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  48250. return ground;
  48251. };
  48252. /**
  48253. * Creates a polygon mesh.
  48254. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  48255. * 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.
  48256. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48257. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48258. * 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).
  48259. * Remember you can only change the shape positions, not their number when updating a polygon.
  48260. */
  48261. MeshBuilder.CreatePolygon = function (name, options, scene) {
  48262. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48263. var shape = options.shape;
  48264. var holes = options.holes || [];
  48265. var depth = options.depth || 0;
  48266. var contours = [];
  48267. var hole = [];
  48268. for (var i = 0; i < shape.length; i++) {
  48269. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  48270. }
  48271. var epsilon = 0.00000001;
  48272. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  48273. contours.pop();
  48274. }
  48275. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  48276. for (var hNb = 0; hNb < holes.length; hNb++) {
  48277. hole = [];
  48278. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  48279. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  48280. }
  48281. polygonTriangulation.addHole(hole);
  48282. }
  48283. var polygon = polygonTriangulation.build(options.updatable, depth);
  48284. polygon._originalBuilderSideOrientation = options.sideOrientation;
  48285. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  48286. vertexData.applyToMesh(polygon, options.updatable);
  48287. return polygon;
  48288. };
  48289. ;
  48290. /**
  48291. * Creates an extruded polygon mesh, with depth in the Y direction.
  48292. * 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).
  48293. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  48294. */
  48295. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  48296. return MeshBuilder.CreatePolygon(name, options, scene);
  48297. };
  48298. ;
  48299. /**
  48300. * Creates a tube mesh.
  48301. * 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.
  48302. *
  48303. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  48304. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  48305. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  48306. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  48307. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  48308. * 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.
  48309. * It must return a radius value (positive float) :
  48310. * ```javascript
  48311. * var radiusFunction = function(i, distance) {
  48312. * // do things
  48313. * return radius; }
  48314. * ```
  48315. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  48316. * 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
  48317. * 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
  48318. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48319. * 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).
  48320. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48321. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48322. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48323. */
  48324. MeshBuilder.CreateTube = function (name, options, scene) {
  48325. var path = options.path;
  48326. var instance = options.instance;
  48327. var radius = 1.0;
  48328. if (instance) {
  48329. radius = instance.radius;
  48330. }
  48331. if (options.radius !== undefined) {
  48332. radius = options.radius;
  48333. }
  48334. ;
  48335. var tessellation = options.tessellation || 64 | 0;
  48336. var radiusFunction = options.radiusFunction || null;
  48337. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  48338. var invertUV = options.invertUV || false;
  48339. var updatable = options.updatable;
  48340. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48341. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  48342. // tube geometry
  48343. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  48344. var tangents = path3D.getTangents();
  48345. var normals = path3D.getNormals();
  48346. var distances = path3D.getDistances();
  48347. var pi2 = Math.PI * 2;
  48348. var step = pi2 / tessellation * arc;
  48349. var returnRadius = function () { return radius; };
  48350. var radiusFunctionFinal = radiusFunction || returnRadius;
  48351. var circlePath;
  48352. var rad;
  48353. var normal;
  48354. var rotated;
  48355. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  48356. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  48357. for (var i = 0; i < path.length; i++) {
  48358. rad = radiusFunctionFinal(i, distances[i]); // current radius
  48359. circlePath = Array(); // current circle array
  48360. normal = normals[i]; // current normal
  48361. for (var t = 0; t < tessellation; t++) {
  48362. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  48363. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  48364. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  48365. rotated.scaleInPlace(rad).addInPlace(path[i]);
  48366. circlePath[t] = rotated;
  48367. }
  48368. circlePaths[index] = circlePath;
  48369. index++;
  48370. }
  48371. // cap
  48372. var capPath = function (nbPoints, pathIndex) {
  48373. var pointCap = Array();
  48374. for (var i = 0; i < nbPoints; i++) {
  48375. pointCap.push(path[pathIndex]);
  48376. }
  48377. return pointCap;
  48378. };
  48379. switch (cap) {
  48380. case BABYLON.Mesh.NO_CAP:
  48381. break;
  48382. case BABYLON.Mesh.CAP_START:
  48383. circlePaths[0] = capPath(tessellation, 0);
  48384. circlePaths[1] = circlePaths[2].slice(0);
  48385. break;
  48386. case BABYLON.Mesh.CAP_END:
  48387. circlePaths[index] = circlePaths[index - 1].slice(0);
  48388. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  48389. break;
  48390. case BABYLON.Mesh.CAP_ALL:
  48391. circlePaths[0] = capPath(tessellation, 0);
  48392. circlePaths[1] = circlePaths[2].slice(0);
  48393. circlePaths[index] = circlePaths[index - 1].slice(0);
  48394. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  48395. break;
  48396. default:
  48397. break;
  48398. }
  48399. return circlePaths;
  48400. };
  48401. var path3D;
  48402. var pathArray;
  48403. if (instance) {
  48404. var arc = options.arc || instance.arc;
  48405. path3D = (instance.path3D).update(path);
  48406. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  48407. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  48408. instance.path3D = path3D;
  48409. instance.pathArray = pathArray;
  48410. instance.arc = arc;
  48411. instance.radius = radius;
  48412. return instance;
  48413. }
  48414. // tube creation
  48415. path3D = new BABYLON.Path3D(path);
  48416. var newPathArray = new Array();
  48417. cap = (cap < 0 || cap > 3) ? 0 : cap;
  48418. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  48419. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  48420. tube.pathArray = pathArray;
  48421. tube.path3D = path3D;
  48422. tube.tessellation = tessellation;
  48423. tube.cap = cap;
  48424. tube.arc = options.arc;
  48425. tube.radius = radius;
  48426. return tube;
  48427. };
  48428. /**
  48429. * Creates a polyhedron mesh.
  48430. *
  48431. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  48432. * 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
  48433. * to choose the wanted type.
  48434. * The parameter `size` (positive float, default 1) sets the polygon size.
  48435. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  48436. * 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`.
  48437. * 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
  48438. * 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)`).
  48439. * 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
  48440. * 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.
  48441. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48442. * 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).
  48443. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48444. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48445. */
  48446. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  48447. var polyhedron = new BABYLON.Mesh(name, scene);
  48448. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48449. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  48450. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  48451. vertexData.applyToMesh(polyhedron, options.updatable);
  48452. return polyhedron;
  48453. };
  48454. /**
  48455. * Creates a decal mesh.
  48456. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  48457. * 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.
  48458. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  48459. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  48460. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  48461. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  48462. */
  48463. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  48464. var indices = sourceMesh.getIndices();
  48465. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48466. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48467. var position = options.position || BABYLON.Vector3.Zero();
  48468. var normal = options.normal || BABYLON.Vector3.Up();
  48469. var size = options.size || BABYLON.Vector3.One();
  48470. var angle = options.angle || 0;
  48471. // Getting correct rotation
  48472. if (!normal) {
  48473. var target = new BABYLON.Vector3(0, 0, 1);
  48474. var camera = sourceMesh.getScene().activeCamera;
  48475. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  48476. normal = camera.globalPosition.subtract(cameraWorldTarget);
  48477. }
  48478. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  48479. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  48480. var pitch = Math.atan2(normal.y, len);
  48481. // Matrix
  48482. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  48483. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  48484. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  48485. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  48486. var vertexData = new BABYLON.VertexData();
  48487. vertexData.indices = [];
  48488. vertexData.positions = [];
  48489. vertexData.normals = [];
  48490. vertexData.uvs = [];
  48491. var currentVertexDataIndex = 0;
  48492. var extractDecalVector3 = function (indexId) {
  48493. var result = new BABYLON.PositionNormalVertex();
  48494. if (!indices || !positions || !normals) {
  48495. return result;
  48496. }
  48497. var vertexId = indices[indexId];
  48498. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  48499. // Send vector to decal local world
  48500. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  48501. // Get normal
  48502. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  48503. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  48504. return result;
  48505. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  48506. var clip = function (vertices, axis) {
  48507. if (vertices.length === 0) {
  48508. return vertices;
  48509. }
  48510. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  48511. var clipVertices = function (v0, v1) {
  48512. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  48513. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  48514. };
  48515. var result = new Array();
  48516. for (var index = 0; index < vertices.length; index += 3) {
  48517. var v1Out;
  48518. var v2Out;
  48519. var v3Out;
  48520. var total = 0;
  48521. var nV1 = null;
  48522. var nV2 = null;
  48523. var nV3 = null;
  48524. var nV4 = null;
  48525. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  48526. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  48527. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  48528. v1Out = d1 > 0;
  48529. v2Out = d2 > 0;
  48530. v3Out = d3 > 0;
  48531. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  48532. switch (total) {
  48533. case 0:
  48534. result.push(vertices[index]);
  48535. result.push(vertices[index + 1]);
  48536. result.push(vertices[index + 2]);
  48537. break;
  48538. case 1:
  48539. if (v1Out) {
  48540. nV1 = vertices[index + 1];
  48541. nV2 = vertices[index + 2];
  48542. nV3 = clipVertices(vertices[index], nV1);
  48543. nV4 = clipVertices(vertices[index], nV2);
  48544. }
  48545. if (v2Out) {
  48546. nV1 = vertices[index];
  48547. nV2 = vertices[index + 2];
  48548. nV3 = clipVertices(vertices[index + 1], nV1);
  48549. nV4 = clipVertices(vertices[index + 1], nV2);
  48550. result.push(nV3);
  48551. result.push(nV2.clone());
  48552. result.push(nV1.clone());
  48553. result.push(nV2.clone());
  48554. result.push(nV3.clone());
  48555. result.push(nV4);
  48556. break;
  48557. }
  48558. if (v3Out) {
  48559. nV1 = vertices[index];
  48560. nV2 = vertices[index + 1];
  48561. nV3 = clipVertices(vertices[index + 2], nV1);
  48562. nV4 = clipVertices(vertices[index + 2], nV2);
  48563. }
  48564. if (nV1 && nV2 && nV3 && nV4) {
  48565. result.push(nV1.clone());
  48566. result.push(nV2.clone());
  48567. result.push(nV3);
  48568. result.push(nV4);
  48569. result.push(nV3.clone());
  48570. result.push(nV2.clone());
  48571. }
  48572. break;
  48573. case 2:
  48574. if (!v1Out) {
  48575. nV1 = vertices[index].clone();
  48576. nV2 = clipVertices(nV1, vertices[index + 1]);
  48577. nV3 = clipVertices(nV1, vertices[index + 2]);
  48578. result.push(nV1);
  48579. result.push(nV2);
  48580. result.push(nV3);
  48581. }
  48582. if (!v2Out) {
  48583. nV1 = vertices[index + 1].clone();
  48584. nV2 = clipVertices(nV1, vertices[index + 2]);
  48585. nV3 = clipVertices(nV1, vertices[index]);
  48586. result.push(nV1);
  48587. result.push(nV2);
  48588. result.push(nV3);
  48589. }
  48590. if (!v3Out) {
  48591. nV1 = vertices[index + 2].clone();
  48592. nV2 = clipVertices(nV1, vertices[index]);
  48593. nV3 = clipVertices(nV1, vertices[index + 1]);
  48594. result.push(nV1);
  48595. result.push(nV2);
  48596. result.push(nV3);
  48597. }
  48598. break;
  48599. case 3:
  48600. break;
  48601. }
  48602. }
  48603. return result;
  48604. };
  48605. for (var index = 0; index < indices.length; index += 3) {
  48606. var faceVertices = new Array();
  48607. faceVertices.push(extractDecalVector3(index));
  48608. faceVertices.push(extractDecalVector3(index + 1));
  48609. faceVertices.push(extractDecalVector3(index + 2));
  48610. // Clip
  48611. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  48612. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  48613. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  48614. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  48615. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  48616. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  48617. if (faceVertices.length === 0) {
  48618. continue;
  48619. }
  48620. // Add UVs and get back to world
  48621. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  48622. var vertex = faceVertices[vIndex];
  48623. //TODO check for Int32Array | Uint32Array | Uint16Array
  48624. vertexData.indices.push(currentVertexDataIndex);
  48625. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  48626. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  48627. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  48628. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  48629. currentVertexDataIndex++;
  48630. }
  48631. }
  48632. // Return mesh
  48633. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  48634. vertexData.applyToMesh(decal);
  48635. decal.position = position.clone();
  48636. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  48637. return decal;
  48638. };
  48639. // Privates
  48640. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  48641. // extrusion geometry
  48642. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  48643. var tangents = path3D.getTangents();
  48644. var normals = path3D.getNormals();
  48645. var binormals = path3D.getBinormals();
  48646. var distances = path3D.getDistances();
  48647. var angle = 0;
  48648. var returnScale = function () { return scale !== null ? scale : 1; };
  48649. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  48650. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  48651. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  48652. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  48653. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  48654. for (var i = 0; i < curve.length; i++) {
  48655. var shapePath = new Array();
  48656. var angleStep = rotate(i, distances[i]);
  48657. var scaleRatio = scl(i, distances[i]);
  48658. for (var p = 0; p < shape.length; p++) {
  48659. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  48660. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  48661. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  48662. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  48663. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  48664. shapePath[p] = rotated;
  48665. }
  48666. shapePaths[index] = shapePath;
  48667. angle += angleStep;
  48668. index++;
  48669. }
  48670. // cap
  48671. var capPath = function (shapePath) {
  48672. var pointCap = Array();
  48673. var barycenter = BABYLON.Vector3.Zero();
  48674. var i;
  48675. for (i = 0; i < shapePath.length; i++) {
  48676. barycenter.addInPlace(shapePath[i]);
  48677. }
  48678. barycenter.scaleInPlace(1.0 / shapePath.length);
  48679. for (i = 0; i < shapePath.length; i++) {
  48680. pointCap.push(barycenter);
  48681. }
  48682. return pointCap;
  48683. };
  48684. switch (cap) {
  48685. case BABYLON.Mesh.NO_CAP:
  48686. break;
  48687. case BABYLON.Mesh.CAP_START:
  48688. shapePaths[0] = capPath(shapePaths[2]);
  48689. shapePaths[1] = shapePaths[2];
  48690. break;
  48691. case BABYLON.Mesh.CAP_END:
  48692. shapePaths[index] = shapePaths[index - 1];
  48693. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  48694. break;
  48695. case BABYLON.Mesh.CAP_ALL:
  48696. shapePaths[0] = capPath(shapePaths[2]);
  48697. shapePaths[1] = shapePaths[2];
  48698. shapePaths[index] = shapePaths[index - 1];
  48699. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  48700. break;
  48701. default:
  48702. break;
  48703. }
  48704. return shapePaths;
  48705. };
  48706. var path3D;
  48707. var pathArray;
  48708. if (instance) {
  48709. path3D = (instance.path3D).update(curve);
  48710. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  48711. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  48712. return instance;
  48713. }
  48714. // extruded shape creation
  48715. path3D = new BABYLON.Path3D(curve);
  48716. var newShapePaths = new Array();
  48717. cap = (cap < 0 || cap > 3) ? 0 : cap;
  48718. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  48719. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  48720. extrudedGeneric.pathArray = pathArray;
  48721. extrudedGeneric.path3D = path3D;
  48722. extrudedGeneric.cap = cap;
  48723. return extrudedGeneric;
  48724. };
  48725. return MeshBuilder;
  48726. }());
  48727. BABYLON.MeshBuilder = MeshBuilder;
  48728. })(BABYLON || (BABYLON = {}));
  48729. //# sourceMappingURL=babylon.meshBuilder.js.map
  48730. var BABYLON;
  48731. (function (BABYLON) {
  48732. var AudioEngine = /** @class */ (function () {
  48733. function AudioEngine() {
  48734. this._audioContext = null;
  48735. this._audioContextInitialized = false;
  48736. this.canUseWebAudio = false;
  48737. this.WarnedWebAudioUnsupported = false;
  48738. this.unlocked = false;
  48739. this.isMP3supported = false;
  48740. this.isOGGsupported = false;
  48741. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  48742. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  48743. this.canUseWebAudio = true;
  48744. }
  48745. var audioElem = document.createElement('audio');
  48746. try {
  48747. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  48748. this.isMP3supported = true;
  48749. }
  48750. }
  48751. catch (e) {
  48752. // protect error during capability check.
  48753. }
  48754. try {
  48755. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  48756. this.isOGGsupported = true;
  48757. }
  48758. }
  48759. catch (e) {
  48760. // protect error during capability check.
  48761. }
  48762. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  48763. this._unlockiOSaudio();
  48764. }
  48765. else {
  48766. this.unlocked = true;
  48767. }
  48768. }
  48769. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  48770. get: function () {
  48771. if (!this._audioContextInitialized) {
  48772. this._initializeAudioContext();
  48773. }
  48774. return this._audioContext;
  48775. },
  48776. enumerable: true,
  48777. configurable: true
  48778. });
  48779. AudioEngine.prototype._unlockiOSaudio = function () {
  48780. var _this = this;
  48781. var unlockaudio = function () {
  48782. if (!_this.audioContext) {
  48783. return;
  48784. }
  48785. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  48786. var source = _this.audioContext.createBufferSource();
  48787. source.buffer = buffer;
  48788. source.connect(_this.audioContext.destination);
  48789. source.start(0);
  48790. setTimeout(function () {
  48791. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  48792. _this.unlocked = true;
  48793. window.removeEventListener('touchend', unlockaudio, false);
  48794. if (_this.onAudioUnlocked) {
  48795. _this.onAudioUnlocked();
  48796. }
  48797. }
  48798. }, 0);
  48799. };
  48800. window.addEventListener('touchend', unlockaudio, false);
  48801. };
  48802. AudioEngine.prototype._initializeAudioContext = function () {
  48803. try {
  48804. if (this.canUseWebAudio) {
  48805. this._audioContext = new AudioContext();
  48806. // create a global volume gain node
  48807. this.masterGain = this._audioContext.createGain();
  48808. this.masterGain.gain.value = 1;
  48809. this.masterGain.connect(this._audioContext.destination);
  48810. this._audioContextInitialized = true;
  48811. }
  48812. }
  48813. catch (e) {
  48814. this.canUseWebAudio = false;
  48815. BABYLON.Tools.Error("Web Audio: " + e.message);
  48816. }
  48817. };
  48818. AudioEngine.prototype.dispose = function () {
  48819. if (this.canUseWebAudio && this._audioContextInitialized) {
  48820. if (this._connectedAnalyser && this._audioContext) {
  48821. this._connectedAnalyser.stopDebugCanvas();
  48822. this._connectedAnalyser.dispose();
  48823. this.masterGain.disconnect();
  48824. this.masterGain.connect(this._audioContext.destination);
  48825. this._connectedAnalyser = null;
  48826. }
  48827. this.masterGain.gain.value = 1;
  48828. }
  48829. this.WarnedWebAudioUnsupported = false;
  48830. };
  48831. AudioEngine.prototype.getGlobalVolume = function () {
  48832. if (this.canUseWebAudio && this._audioContextInitialized) {
  48833. return this.masterGain.gain.value;
  48834. }
  48835. else {
  48836. return -1;
  48837. }
  48838. };
  48839. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  48840. if (this.canUseWebAudio && this._audioContextInitialized) {
  48841. this.masterGain.gain.value = newVolume;
  48842. }
  48843. };
  48844. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  48845. if (this._connectedAnalyser) {
  48846. this._connectedAnalyser.stopDebugCanvas();
  48847. }
  48848. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  48849. this._connectedAnalyser = analyser;
  48850. this.masterGain.disconnect();
  48851. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  48852. }
  48853. };
  48854. return AudioEngine;
  48855. }());
  48856. BABYLON.AudioEngine = AudioEngine;
  48857. })(BABYLON || (BABYLON = {}));
  48858. //# sourceMappingURL=babylon.audioEngine.js.map
  48859. var BABYLON;
  48860. (function (BABYLON) {
  48861. var Sound = /** @class */ (function () {
  48862. /**
  48863. * Create a sound and attach it to a scene
  48864. * @param name Name of your sound
  48865. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  48866. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  48867. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  48868. */
  48869. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  48870. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  48871. var _this = this;
  48872. this.autoplay = false;
  48873. this.loop = false;
  48874. this.useCustomAttenuation = false;
  48875. this.spatialSound = false;
  48876. this.refDistance = 1;
  48877. this.rolloffFactor = 1;
  48878. this.maxDistance = 100;
  48879. this.distanceModel = "linear";
  48880. this._panningModel = "equalpower";
  48881. this._playbackRate = 1;
  48882. this._streaming = false;
  48883. this._startTime = 0;
  48884. this._startOffset = 0;
  48885. this._position = BABYLON.Vector3.Zero();
  48886. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  48887. this._volume = 1;
  48888. this._isReadyToPlay = false;
  48889. this.isPlaying = false;
  48890. this.isPaused = false;
  48891. this._isDirectional = false;
  48892. // Used if you'd like to create a directional sound.
  48893. // If not set, the sound will be omnidirectional
  48894. this._coneInnerAngle = 360;
  48895. this._coneOuterAngle = 360;
  48896. this._coneOuterGain = 0;
  48897. this._isOutputConnected = false;
  48898. this._urlType = "Unknown";
  48899. this.name = name;
  48900. this._scene = scene;
  48901. this._readyToPlayCallback = readyToPlayCallback;
  48902. // Default custom attenuation function is a linear attenuation
  48903. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  48904. if (currentDistance < maxDistance) {
  48905. return currentVolume * (1 - currentDistance / maxDistance);
  48906. }
  48907. else {
  48908. return 0;
  48909. }
  48910. };
  48911. if (options) {
  48912. this.autoplay = options.autoplay || false;
  48913. this.loop = options.loop || false;
  48914. // if volume === 0, we need another way to check this option
  48915. if (options.volume !== undefined) {
  48916. this._volume = options.volume;
  48917. }
  48918. this.spatialSound = options.spatialSound || false;
  48919. this.maxDistance = options.maxDistance || 100;
  48920. this.useCustomAttenuation = options.useCustomAttenuation || false;
  48921. this.rolloffFactor = options.rolloffFactor || 1;
  48922. this.refDistance = options.refDistance || 1;
  48923. this.distanceModel = options.distanceModel || "linear";
  48924. this._playbackRate = options.playbackRate || 1;
  48925. this._streaming = options.streaming || false;
  48926. }
  48927. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48928. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  48929. this._soundGain.gain.value = this._volume;
  48930. this._inputAudioNode = this._soundGain;
  48931. this._ouputAudioNode = this._soundGain;
  48932. if (this.spatialSound) {
  48933. this._createSpatialParameters();
  48934. }
  48935. this._scene.mainSoundTrack.AddSound(this);
  48936. var validParameter = true;
  48937. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  48938. if (urlOrArrayBuffer) {
  48939. if (typeof (urlOrArrayBuffer) === "string")
  48940. this._urlType = "String";
  48941. if (Array.isArray(urlOrArrayBuffer))
  48942. this._urlType = "Array";
  48943. if (urlOrArrayBuffer instanceof ArrayBuffer)
  48944. this._urlType = "ArrayBuffer";
  48945. var urls = [];
  48946. var codecSupportedFound = false;
  48947. switch (this._urlType) {
  48948. case "ArrayBuffer":
  48949. if (urlOrArrayBuffer.byteLength > 0) {
  48950. codecSupportedFound = true;
  48951. this._soundLoaded(urlOrArrayBuffer);
  48952. }
  48953. break;
  48954. case "String":
  48955. urls.push(urlOrArrayBuffer);
  48956. case "Array":
  48957. if (urls.length === 0)
  48958. urls = urlOrArrayBuffer;
  48959. // If we found a supported format, we load it immediately and stop the loop
  48960. for (var i = 0; i < urls.length; i++) {
  48961. var url = urls[i];
  48962. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  48963. codecSupportedFound = true;
  48964. }
  48965. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  48966. codecSupportedFound = true;
  48967. }
  48968. if (url.indexOf(".wav", url.length - 4) !== -1) {
  48969. codecSupportedFound = true;
  48970. }
  48971. if (url.indexOf("blob:") !== -1) {
  48972. codecSupportedFound = true;
  48973. }
  48974. if (codecSupportedFound) {
  48975. // Loading sound using XHR2
  48976. if (!this._streaming) {
  48977. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, undefined, this._scene.database, true);
  48978. }
  48979. else {
  48980. this._htmlAudioElement = new Audio(url);
  48981. this._htmlAudioElement.controls = false;
  48982. this._htmlAudioElement.loop = this.loop;
  48983. this._htmlAudioElement.crossOrigin = "anonymous";
  48984. this._htmlAudioElement.preload = "auto";
  48985. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  48986. _this._isReadyToPlay = true;
  48987. if (_this.autoplay) {
  48988. _this.play();
  48989. }
  48990. if (_this._readyToPlayCallback) {
  48991. _this._readyToPlayCallback();
  48992. }
  48993. });
  48994. document.body.appendChild(this._htmlAudioElement);
  48995. }
  48996. break;
  48997. }
  48998. }
  48999. break;
  49000. default:
  49001. validParameter = false;
  49002. break;
  49003. }
  49004. if (!validParameter) {
  49005. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  49006. }
  49007. else {
  49008. if (!codecSupportedFound) {
  49009. this._isReadyToPlay = true;
  49010. // Simulating a ready to play event to avoid breaking code path
  49011. if (this._readyToPlayCallback) {
  49012. window.setTimeout(function () {
  49013. if (_this._readyToPlayCallback) {
  49014. _this._readyToPlayCallback();
  49015. }
  49016. }, 1000);
  49017. }
  49018. }
  49019. }
  49020. }
  49021. }
  49022. else {
  49023. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  49024. this._scene.mainSoundTrack.AddSound(this);
  49025. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  49026. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  49027. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  49028. }
  49029. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  49030. if (this._readyToPlayCallback) {
  49031. window.setTimeout(function () {
  49032. if (_this._readyToPlayCallback) {
  49033. _this._readyToPlayCallback();
  49034. }
  49035. }, 1000);
  49036. }
  49037. }
  49038. }
  49039. Sound.prototype.dispose = function () {
  49040. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  49041. if (this.isPlaying) {
  49042. this.stop();
  49043. }
  49044. this._isReadyToPlay = false;
  49045. if (this.soundTrackId === -1) {
  49046. this._scene.mainSoundTrack.RemoveSound(this);
  49047. }
  49048. else {
  49049. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  49050. }
  49051. if (this._soundGain) {
  49052. this._soundGain.disconnect();
  49053. this._soundGain = null;
  49054. }
  49055. if (this._soundPanner) {
  49056. this._soundPanner.disconnect();
  49057. this._soundPanner = null;
  49058. }
  49059. if (this._soundSource) {
  49060. this._soundSource.disconnect();
  49061. this._soundSource = null;
  49062. }
  49063. this._audioBuffer = null;
  49064. if (this._htmlAudioElement) {
  49065. this._htmlAudioElement.pause();
  49066. this._htmlAudioElement.src = "";
  49067. document.body.removeChild(this._htmlAudioElement);
  49068. }
  49069. if (this._connectedMesh && this._registerFunc) {
  49070. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  49071. this._connectedMesh = null;
  49072. }
  49073. }
  49074. };
  49075. Sound.prototype.isReady = function () {
  49076. return this._isReadyToPlay;
  49077. };
  49078. Sound.prototype._soundLoaded = function (audioData) {
  49079. var _this = this;
  49080. if (!BABYLON.Engine.audioEngine.audioContext) {
  49081. return;
  49082. }
  49083. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  49084. _this._audioBuffer = buffer;
  49085. _this._isReadyToPlay = true;
  49086. if (_this.autoplay) {
  49087. _this.play();
  49088. }
  49089. if (_this._readyToPlayCallback) {
  49090. _this._readyToPlayCallback();
  49091. }
  49092. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  49093. };
  49094. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  49095. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49096. this._audioBuffer = audioBuffer;
  49097. this._isReadyToPlay = true;
  49098. }
  49099. };
  49100. Sound.prototype.updateOptions = function (options) {
  49101. if (options) {
  49102. this.loop = options.loop || this.loop;
  49103. this.maxDistance = options.maxDistance || this.maxDistance;
  49104. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  49105. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  49106. this.refDistance = options.refDistance || this.refDistance;
  49107. this.distanceModel = options.distanceModel || this.distanceModel;
  49108. this._playbackRate = options.playbackRate || this._playbackRate;
  49109. this._updateSpatialParameters();
  49110. if (this.isPlaying) {
  49111. if (this._streaming) {
  49112. this._htmlAudioElement.playbackRate = this._playbackRate;
  49113. }
  49114. else {
  49115. if (this._soundSource) {
  49116. this._soundSource.playbackRate.value = this._playbackRate;
  49117. }
  49118. }
  49119. }
  49120. }
  49121. };
  49122. Sound.prototype._createSpatialParameters = function () {
  49123. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  49124. if (this._scene.headphone) {
  49125. this._panningModel = "HRTF";
  49126. }
  49127. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  49128. this._updateSpatialParameters();
  49129. this._soundPanner.connect(this._ouputAudioNode);
  49130. this._inputAudioNode = this._soundPanner;
  49131. }
  49132. };
  49133. Sound.prototype._updateSpatialParameters = function () {
  49134. if (this.spatialSound && this._soundPanner) {
  49135. if (this.useCustomAttenuation) {
  49136. // Tricks to disable in a way embedded Web Audio attenuation
  49137. this._soundPanner.distanceModel = "linear";
  49138. this._soundPanner.maxDistance = Number.MAX_VALUE;
  49139. this._soundPanner.refDistance = 1;
  49140. this._soundPanner.rolloffFactor = 1;
  49141. this._soundPanner.panningModel = this._panningModel;
  49142. }
  49143. else {
  49144. this._soundPanner.distanceModel = this.distanceModel;
  49145. this._soundPanner.maxDistance = this.maxDistance;
  49146. this._soundPanner.refDistance = this.refDistance;
  49147. this._soundPanner.rolloffFactor = this.rolloffFactor;
  49148. this._soundPanner.panningModel = this._panningModel;
  49149. }
  49150. }
  49151. };
  49152. Sound.prototype.switchPanningModelToHRTF = function () {
  49153. this._panningModel = "HRTF";
  49154. this._switchPanningModel();
  49155. };
  49156. Sound.prototype.switchPanningModelToEqualPower = function () {
  49157. this._panningModel = "equalpower";
  49158. this._switchPanningModel();
  49159. };
  49160. Sound.prototype._switchPanningModel = function () {
  49161. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  49162. this._soundPanner.panningModel = this._panningModel;
  49163. }
  49164. };
  49165. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  49166. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49167. if (this._isOutputConnected) {
  49168. this._ouputAudioNode.disconnect();
  49169. }
  49170. this._ouputAudioNode.connect(soundTrackAudioNode);
  49171. this._isOutputConnected = true;
  49172. }
  49173. };
  49174. /**
  49175. * Transform this sound into a directional source
  49176. * @param coneInnerAngle Size of the inner cone in degree
  49177. * @param coneOuterAngle Size of the outer cone in degree
  49178. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  49179. */
  49180. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  49181. if (coneOuterAngle < coneInnerAngle) {
  49182. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  49183. return;
  49184. }
  49185. this._coneInnerAngle = coneInnerAngle;
  49186. this._coneOuterAngle = coneOuterAngle;
  49187. this._coneOuterGain = coneOuterGain;
  49188. this._isDirectional = true;
  49189. if (this.isPlaying && this.loop) {
  49190. this.stop();
  49191. this.play();
  49192. }
  49193. };
  49194. Sound.prototype.setPosition = function (newPosition) {
  49195. this._position = newPosition;
  49196. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  49197. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  49198. }
  49199. };
  49200. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  49201. this._localDirection = newLocalDirection;
  49202. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  49203. this._updateDirection();
  49204. }
  49205. };
  49206. Sound.prototype._updateDirection = function () {
  49207. if (!this._connectedMesh || !this._soundPanner) {
  49208. return;
  49209. }
  49210. var mat = this._connectedMesh.getWorldMatrix();
  49211. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  49212. direction.normalize();
  49213. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  49214. };
  49215. Sound.prototype.updateDistanceFromListener = function () {
  49216. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  49217. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  49218. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  49219. }
  49220. };
  49221. Sound.prototype.setAttenuationFunction = function (callback) {
  49222. this._customAttenuationFunction = callback;
  49223. };
  49224. /**
  49225. * Play the sound
  49226. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  49227. * @param offset (optional) Start the sound setting it at a specific time
  49228. */
  49229. Sound.prototype.play = function (time, offset) {
  49230. var _this = this;
  49231. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  49232. try {
  49233. if (this._startOffset < 0) {
  49234. time = -this._startOffset;
  49235. this._startOffset = 0;
  49236. }
  49237. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  49238. if (!this._soundSource || !this._streamingSource) {
  49239. if (this.spatialSound && this._soundPanner) {
  49240. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  49241. if (this._isDirectional) {
  49242. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  49243. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  49244. this._soundPanner.coneOuterGain = this._coneOuterGain;
  49245. if (this._connectedMesh) {
  49246. this._updateDirection();
  49247. }
  49248. else {
  49249. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  49250. }
  49251. }
  49252. }
  49253. }
  49254. if (this._streaming) {
  49255. if (!this._streamingSource) {
  49256. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  49257. this._htmlAudioElement.onended = function () { _this._onended(); };
  49258. this._htmlAudioElement.playbackRate = this._playbackRate;
  49259. }
  49260. this._streamingSource.disconnect();
  49261. this._streamingSource.connect(this._inputAudioNode);
  49262. this._htmlAudioElement.play();
  49263. }
  49264. else {
  49265. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  49266. this._soundSource.buffer = this._audioBuffer;
  49267. this._soundSource.connect(this._inputAudioNode);
  49268. this._soundSource.loop = this.loop;
  49269. this._soundSource.playbackRate.value = this._playbackRate;
  49270. this._soundSource.onended = function () { _this._onended(); };
  49271. if (this._soundSource.buffer) {
  49272. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  49273. }
  49274. }
  49275. this._startTime = startTime;
  49276. this.isPlaying = true;
  49277. this.isPaused = false;
  49278. }
  49279. catch (ex) {
  49280. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  49281. }
  49282. }
  49283. };
  49284. Sound.prototype._onended = function () {
  49285. this.isPlaying = false;
  49286. if (this.onended) {
  49287. this.onended();
  49288. }
  49289. };
  49290. /**
  49291. * Stop the sound
  49292. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  49293. */
  49294. Sound.prototype.stop = function (time) {
  49295. if (this.isPlaying) {
  49296. if (this._streaming) {
  49297. this._htmlAudioElement.pause();
  49298. // Test needed for Firefox or it will generate an Invalid State Error
  49299. if (this._htmlAudioElement.currentTime > 0) {
  49300. this._htmlAudioElement.currentTime = 0;
  49301. }
  49302. }
  49303. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  49304. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  49305. this._soundSource.stop(stopTime);
  49306. this._soundSource.onended = function () { };
  49307. if (!this.isPaused) {
  49308. this._startOffset = 0;
  49309. }
  49310. }
  49311. this.isPlaying = false;
  49312. }
  49313. };
  49314. Sound.prototype.pause = function () {
  49315. if (this.isPlaying) {
  49316. this.isPaused = true;
  49317. if (this._streaming) {
  49318. this._htmlAudioElement.pause();
  49319. }
  49320. else if (BABYLON.Engine.audioEngine.audioContext) {
  49321. this.stop(0);
  49322. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  49323. }
  49324. }
  49325. };
  49326. Sound.prototype.setVolume = function (newVolume, time) {
  49327. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  49328. if (time && BABYLON.Engine.audioEngine.audioContext) {
  49329. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  49330. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  49331. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  49332. }
  49333. else {
  49334. this._soundGain.gain.value = newVolume;
  49335. }
  49336. }
  49337. this._volume = newVolume;
  49338. };
  49339. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  49340. this._playbackRate = newPlaybackRate;
  49341. if (this.isPlaying) {
  49342. if (this._streaming) {
  49343. this._htmlAudioElement.playbackRate = this._playbackRate;
  49344. }
  49345. else if (this._soundSource) {
  49346. this._soundSource.playbackRate.value = this._playbackRate;
  49347. }
  49348. }
  49349. };
  49350. Sound.prototype.getVolume = function () {
  49351. return this._volume;
  49352. };
  49353. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  49354. var _this = this;
  49355. if (this._connectedMesh && this._registerFunc) {
  49356. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  49357. this._registerFunc = null;
  49358. }
  49359. this._connectedMesh = meshToConnectTo;
  49360. if (!this.spatialSound) {
  49361. this.spatialSound = true;
  49362. this._createSpatialParameters();
  49363. if (this.isPlaying && this.loop) {
  49364. this.stop();
  49365. this.play();
  49366. }
  49367. }
  49368. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  49369. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  49370. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  49371. };
  49372. Sound.prototype.detachFromMesh = function () {
  49373. if (this._connectedMesh && this._registerFunc) {
  49374. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  49375. this._registerFunc = null;
  49376. this._connectedMesh = null;
  49377. }
  49378. };
  49379. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  49380. var boundingInfo = connectedMesh.getBoundingInfo();
  49381. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  49382. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  49383. this._updateDirection();
  49384. }
  49385. };
  49386. Sound.prototype.clone = function () {
  49387. var _this = this;
  49388. if (!this._streaming) {
  49389. var setBufferAndRun = function () {
  49390. if (_this._isReadyToPlay) {
  49391. clonedSound._audioBuffer = _this.getAudioBuffer();
  49392. clonedSound._isReadyToPlay = true;
  49393. if (clonedSound.autoplay) {
  49394. clonedSound.play();
  49395. }
  49396. }
  49397. else {
  49398. window.setTimeout(setBufferAndRun, 300);
  49399. }
  49400. };
  49401. var currentOptions = {
  49402. autoplay: this.autoplay, loop: this.loop,
  49403. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  49404. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  49405. refDistance: this.refDistance, distanceModel: this.distanceModel
  49406. };
  49407. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  49408. if (this.useCustomAttenuation) {
  49409. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  49410. }
  49411. clonedSound.setPosition(this._position);
  49412. clonedSound.setPlaybackRate(this._playbackRate);
  49413. setBufferAndRun();
  49414. return clonedSound;
  49415. }
  49416. else {
  49417. return null;
  49418. }
  49419. };
  49420. Sound.prototype.getAudioBuffer = function () {
  49421. return this._audioBuffer;
  49422. };
  49423. Sound.prototype.serialize = function () {
  49424. var serializationObject = {
  49425. name: this.name,
  49426. url: this.name,
  49427. autoplay: this.autoplay,
  49428. loop: this.loop,
  49429. volume: this._volume,
  49430. spatialSound: this.spatialSound,
  49431. maxDistance: this.maxDistance,
  49432. rolloffFactor: this.rolloffFactor,
  49433. refDistance: this.refDistance,
  49434. distanceModel: this.distanceModel,
  49435. playbackRate: this._playbackRate,
  49436. panningModel: this._panningModel,
  49437. soundTrackId: this.soundTrackId
  49438. };
  49439. if (this.spatialSound) {
  49440. if (this._connectedMesh)
  49441. serializationObject.connectedMeshId = this._connectedMesh.id;
  49442. serializationObject.position = this._position.asArray();
  49443. serializationObject.refDistance = this.refDistance;
  49444. serializationObject.distanceModel = this.distanceModel;
  49445. serializationObject.isDirectional = this._isDirectional;
  49446. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  49447. serializationObject.coneInnerAngle = this._coneInnerAngle;
  49448. serializationObject.coneOuterAngle = this._coneOuterAngle;
  49449. serializationObject.coneOuterGain = this._coneOuterGain;
  49450. }
  49451. return serializationObject;
  49452. };
  49453. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  49454. var soundName = parsedSound.name;
  49455. var soundUrl;
  49456. if (parsedSound.url) {
  49457. soundUrl = rootUrl + parsedSound.url;
  49458. }
  49459. else {
  49460. soundUrl = rootUrl + soundName;
  49461. }
  49462. var options = {
  49463. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  49464. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  49465. rolloffFactor: parsedSound.rolloffFactor,
  49466. refDistance: parsedSound.refDistance,
  49467. distanceModel: parsedSound.distanceModel,
  49468. playbackRate: parsedSound.playbackRate
  49469. };
  49470. var newSound;
  49471. if (!sourceSound) {
  49472. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  49473. scene._addPendingData(newSound);
  49474. }
  49475. else {
  49476. var setBufferAndRun = function () {
  49477. if (sourceSound._isReadyToPlay) {
  49478. newSound._audioBuffer = sourceSound.getAudioBuffer();
  49479. newSound._isReadyToPlay = true;
  49480. if (newSound.autoplay) {
  49481. newSound.play();
  49482. }
  49483. }
  49484. else {
  49485. window.setTimeout(setBufferAndRun, 300);
  49486. }
  49487. };
  49488. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  49489. setBufferAndRun();
  49490. }
  49491. if (parsedSound.position) {
  49492. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  49493. newSound.setPosition(soundPosition);
  49494. }
  49495. if (parsedSound.isDirectional) {
  49496. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  49497. if (parsedSound.localDirectionToMesh) {
  49498. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  49499. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  49500. }
  49501. }
  49502. if (parsedSound.connectedMeshId) {
  49503. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  49504. if (connectedMesh) {
  49505. newSound.attachToMesh(connectedMesh);
  49506. }
  49507. }
  49508. return newSound;
  49509. };
  49510. return Sound;
  49511. }());
  49512. BABYLON.Sound = Sound;
  49513. })(BABYLON || (BABYLON = {}));
  49514. //# sourceMappingURL=babylon.sound.js.map
  49515. var BABYLON;
  49516. (function (BABYLON) {
  49517. var SoundTrack = /** @class */ (function () {
  49518. function SoundTrack(scene, options) {
  49519. this.id = -1;
  49520. this._isMainTrack = false;
  49521. this._isInitialized = false;
  49522. this._scene = scene;
  49523. this.soundCollection = new Array();
  49524. this._options = options;
  49525. if (!this._isMainTrack) {
  49526. this._scene.soundTracks.push(this);
  49527. this.id = this._scene.soundTracks.length - 1;
  49528. }
  49529. }
  49530. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  49531. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  49532. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  49533. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  49534. if (this._options) {
  49535. if (this._options.volume) {
  49536. this._outputAudioNode.gain.value = this._options.volume;
  49537. }
  49538. if (this._options.mainTrack) {
  49539. this._isMainTrack = this._options.mainTrack;
  49540. }
  49541. }
  49542. this._isInitialized = true;
  49543. }
  49544. };
  49545. SoundTrack.prototype.dispose = function () {
  49546. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49547. if (this._connectedAnalyser) {
  49548. this._connectedAnalyser.stopDebugCanvas();
  49549. }
  49550. while (this.soundCollection.length) {
  49551. this.soundCollection[0].dispose();
  49552. }
  49553. if (this._outputAudioNode) {
  49554. this._outputAudioNode.disconnect();
  49555. }
  49556. this._outputAudioNode = null;
  49557. }
  49558. };
  49559. SoundTrack.prototype.AddSound = function (sound) {
  49560. if (!this._isInitialized) {
  49561. this._initializeSoundTrackAudioGraph();
  49562. }
  49563. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  49564. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  49565. }
  49566. if (sound.soundTrackId) {
  49567. if (sound.soundTrackId === -1) {
  49568. this._scene.mainSoundTrack.RemoveSound(sound);
  49569. }
  49570. else {
  49571. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  49572. }
  49573. }
  49574. this.soundCollection.push(sound);
  49575. sound.soundTrackId = this.id;
  49576. };
  49577. SoundTrack.prototype.RemoveSound = function (sound) {
  49578. var index = this.soundCollection.indexOf(sound);
  49579. if (index !== -1) {
  49580. this.soundCollection.splice(index, 1);
  49581. }
  49582. };
  49583. SoundTrack.prototype.setVolume = function (newVolume) {
  49584. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  49585. this._outputAudioNode.gain.value = newVolume;
  49586. }
  49587. };
  49588. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  49589. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49590. for (var i = 0; i < this.soundCollection.length; i++) {
  49591. this.soundCollection[i].switchPanningModelToHRTF();
  49592. }
  49593. }
  49594. };
  49595. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  49596. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49597. for (var i = 0; i < this.soundCollection.length; i++) {
  49598. this.soundCollection[i].switchPanningModelToEqualPower();
  49599. }
  49600. }
  49601. };
  49602. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  49603. if (this._connectedAnalyser) {
  49604. this._connectedAnalyser.stopDebugCanvas();
  49605. }
  49606. this._connectedAnalyser = analyser;
  49607. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  49608. this._outputAudioNode.disconnect();
  49609. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  49610. }
  49611. };
  49612. return SoundTrack;
  49613. }());
  49614. BABYLON.SoundTrack = SoundTrack;
  49615. })(BABYLON || (BABYLON = {}));
  49616. //# sourceMappingURL=babylon.soundtrack.js.map
  49617. var BABYLON;
  49618. (function (BABYLON) {
  49619. var Analyser = /** @class */ (function () {
  49620. function Analyser(scene) {
  49621. this.SMOOTHING = 0.75;
  49622. this.FFT_SIZE = 512;
  49623. this.BARGRAPHAMPLITUDE = 256;
  49624. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  49625. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  49626. this._scene = scene;
  49627. this._audioEngine = BABYLON.Engine.audioEngine;
  49628. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  49629. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  49630. this._webAudioAnalyser.minDecibels = -140;
  49631. this._webAudioAnalyser.maxDecibels = 0;
  49632. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  49633. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  49634. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  49635. }
  49636. }
  49637. Analyser.prototype.getFrequencyBinCount = function () {
  49638. if (this._audioEngine.canUseWebAudio) {
  49639. return this._webAudioAnalyser.frequencyBinCount;
  49640. }
  49641. else {
  49642. return 0;
  49643. }
  49644. };
  49645. Analyser.prototype.getByteFrequencyData = function () {
  49646. if (this._audioEngine.canUseWebAudio) {
  49647. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49648. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49649. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  49650. }
  49651. return this._byteFreqs;
  49652. };
  49653. Analyser.prototype.getByteTimeDomainData = function () {
  49654. if (this._audioEngine.canUseWebAudio) {
  49655. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49656. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49657. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  49658. }
  49659. return this._byteTime;
  49660. };
  49661. Analyser.prototype.getFloatFrequencyData = function () {
  49662. if (this._audioEngine.canUseWebAudio) {
  49663. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49664. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49665. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  49666. }
  49667. return this._floatFreqs;
  49668. };
  49669. Analyser.prototype.drawDebugCanvas = function () {
  49670. var _this = this;
  49671. if (this._audioEngine.canUseWebAudio) {
  49672. if (!this._debugCanvas) {
  49673. this._debugCanvas = document.createElement("canvas");
  49674. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  49675. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  49676. this._debugCanvas.style.position = "absolute";
  49677. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  49678. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  49679. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  49680. document.body.appendChild(this._debugCanvas);
  49681. this._registerFunc = function () {
  49682. _this.drawDebugCanvas();
  49683. };
  49684. this._scene.registerBeforeRender(this._registerFunc);
  49685. }
  49686. if (this._registerFunc && this._debugCanvasContext) {
  49687. var workingArray = this.getByteFrequencyData();
  49688. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  49689. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  49690. // Draw the frequency domain chart.
  49691. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  49692. var value = workingArray[i];
  49693. var percent = value / this.BARGRAPHAMPLITUDE;
  49694. var height = this.DEBUGCANVASSIZE.height * percent;
  49695. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  49696. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  49697. var hue = i / this.getFrequencyBinCount() * 360;
  49698. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  49699. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  49700. }
  49701. }
  49702. }
  49703. };
  49704. Analyser.prototype.stopDebugCanvas = function () {
  49705. if (this._debugCanvas) {
  49706. if (this._registerFunc) {
  49707. this._scene.unregisterBeforeRender(this._registerFunc);
  49708. this._registerFunc = null;
  49709. }
  49710. document.body.removeChild(this._debugCanvas);
  49711. this._debugCanvas = null;
  49712. this._debugCanvasContext = null;
  49713. }
  49714. };
  49715. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  49716. if (this._audioEngine.canUseWebAudio) {
  49717. inputAudioNode.connect(this._webAudioAnalyser);
  49718. this._webAudioAnalyser.connect(outputAudioNode);
  49719. }
  49720. };
  49721. Analyser.prototype.dispose = function () {
  49722. if (this._audioEngine.canUseWebAudio) {
  49723. this._webAudioAnalyser.disconnect();
  49724. }
  49725. };
  49726. return Analyser;
  49727. }());
  49728. BABYLON.Analyser = Analyser;
  49729. })(BABYLON || (BABYLON = {}));
  49730. //# sourceMappingURL=babylon.analyser.js.map
  49731. var BABYLON;
  49732. (function (BABYLON) {
  49733. var CubeTexture = /** @class */ (function (_super) {
  49734. __extends(CubeTexture, _super);
  49735. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  49736. if (extensions === void 0) { extensions = null; }
  49737. if (noMipmap === void 0) { noMipmap = false; }
  49738. if (files === void 0) { files = null; }
  49739. if (onLoad === void 0) { onLoad = null; }
  49740. if (onError === void 0) { onError = null; }
  49741. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  49742. if (prefiltered === void 0) { prefiltered = false; }
  49743. if (forcedExtension === void 0) { forcedExtension = null; }
  49744. var _this = _super.call(this, scene) || this;
  49745. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  49746. _this.name = rootUrl;
  49747. _this.url = rootUrl;
  49748. _this._noMipmap = noMipmap;
  49749. _this.hasAlpha = false;
  49750. _this._format = format;
  49751. _this._prefiltered = prefiltered;
  49752. _this.isCube = true;
  49753. _this._textureMatrix = BABYLON.Matrix.Identity();
  49754. if (prefiltered) {
  49755. _this.gammaSpace = false;
  49756. }
  49757. if (!rootUrl && !files) {
  49758. return _this;
  49759. }
  49760. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  49761. var lastDot = rootUrl.lastIndexOf(".");
  49762. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  49763. var isDDS = (extension === ".dds");
  49764. if (!files) {
  49765. if (!isDDS && !extensions) {
  49766. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  49767. }
  49768. files = [];
  49769. if (extensions) {
  49770. for (var index = 0; index < extensions.length; index++) {
  49771. files.push(rootUrl + extensions[index]);
  49772. }
  49773. }
  49774. }
  49775. if (!_this._texture) {
  49776. if (!scene.useDelayedTextureLoading) {
  49777. if (prefiltered) {
  49778. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  49779. }
  49780. else {
  49781. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  49782. }
  49783. }
  49784. else {
  49785. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  49786. }
  49787. }
  49788. else if (onLoad) {
  49789. if (_this._texture.isReady) {
  49790. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  49791. }
  49792. else {
  49793. _this._texture.onLoadedObservable.add(onLoad);
  49794. }
  49795. }
  49796. return _this;
  49797. }
  49798. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  49799. return new CubeTexture("", scene, null, noMipmap, files);
  49800. };
  49801. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  49802. if (forcedExtension === void 0) { forcedExtension = null; }
  49803. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  49804. };
  49805. // Methods
  49806. CubeTexture.prototype.delayLoad = function () {
  49807. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  49808. return;
  49809. }
  49810. var scene = this.getScene();
  49811. if (!scene) {
  49812. return;
  49813. }
  49814. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  49815. this._texture = this._getFromCache(this.url, this._noMipmap);
  49816. if (!this._texture) {
  49817. if (this._prefiltered) {
  49818. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  49819. }
  49820. else {
  49821. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  49822. }
  49823. }
  49824. };
  49825. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  49826. return this._textureMatrix;
  49827. };
  49828. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  49829. this._textureMatrix = value;
  49830. };
  49831. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  49832. var texture = BABYLON.SerializationHelper.Parse(function () {
  49833. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  49834. }, parsedTexture, scene);
  49835. // Animations
  49836. if (parsedTexture.animations) {
  49837. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  49838. var parsedAnimation = parsedTexture.animations[animationIndex];
  49839. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  49840. }
  49841. }
  49842. return texture;
  49843. };
  49844. CubeTexture.prototype.clone = function () {
  49845. var _this = this;
  49846. return BABYLON.SerializationHelper.Clone(function () {
  49847. var scene = _this.getScene();
  49848. if (!scene) {
  49849. return _this;
  49850. }
  49851. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  49852. }, this);
  49853. };
  49854. return CubeTexture;
  49855. }(BABYLON.BaseTexture));
  49856. BABYLON.CubeTexture = CubeTexture;
  49857. })(BABYLON || (BABYLON = {}));
  49858. //# sourceMappingURL=babylon.cubeTexture.js.map
  49859. var BABYLON;
  49860. (function (BABYLON) {
  49861. var RenderTargetTexture = /** @class */ (function (_super) {
  49862. __extends(RenderTargetTexture, _super);
  49863. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  49864. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  49865. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49866. if (isCube === void 0) { isCube = false; }
  49867. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49868. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  49869. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  49870. if (isMulti === void 0) { isMulti = false; }
  49871. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  49872. _this.isCube = isCube;
  49873. /**
  49874. * Use this list to define the list of mesh you want to render.
  49875. */
  49876. _this.renderList = new Array();
  49877. _this.renderParticles = true;
  49878. _this.renderSprites = false;
  49879. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  49880. _this.ignoreCameraViewport = false;
  49881. // Events
  49882. /**
  49883. * An event triggered when the texture is unbind.
  49884. * @type {BABYLON.Observable}
  49885. */
  49886. _this.onBeforeBindObservable = new BABYLON.Observable();
  49887. /**
  49888. * An event triggered when the texture is unbind.
  49889. * @type {BABYLON.Observable}
  49890. */
  49891. _this.onAfterUnbindObservable = new BABYLON.Observable();
  49892. /**
  49893. * An event triggered before rendering the texture
  49894. * @type {BABYLON.Observable}
  49895. */
  49896. _this.onBeforeRenderObservable = new BABYLON.Observable();
  49897. /**
  49898. * An event triggered after rendering the texture
  49899. * @type {BABYLON.Observable}
  49900. */
  49901. _this.onAfterRenderObservable = new BABYLON.Observable();
  49902. /**
  49903. * An event triggered after the texture clear
  49904. * @type {BABYLON.Observable}
  49905. */
  49906. _this.onClearObservable = new BABYLON.Observable();
  49907. _this._currentRefreshId = -1;
  49908. _this._refreshRate = 1;
  49909. _this._samples = 1;
  49910. scene = _this.getScene();
  49911. if (!scene) {
  49912. return _this;
  49913. }
  49914. _this._engine = scene.getEngine();
  49915. _this.name = name;
  49916. _this.isRenderTarget = true;
  49917. _this._initialSizeParameter = size;
  49918. _this._processSizeParameter(size);
  49919. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  49920. });
  49921. _this._generateMipMaps = generateMipMaps ? true : false;
  49922. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  49923. // Rendering groups
  49924. _this._renderingManager = new BABYLON.RenderingManager(scene);
  49925. if (isMulti) {
  49926. return _this;
  49927. }
  49928. _this._renderTargetOptions = {
  49929. generateMipMaps: generateMipMaps,
  49930. type: type,
  49931. samplingMode: samplingMode,
  49932. generateDepthBuffer: generateDepthBuffer,
  49933. generateStencilBuffer: generateStencilBuffer
  49934. };
  49935. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  49936. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49937. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49938. }
  49939. if (isCube) {
  49940. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  49941. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  49942. _this._textureMatrix = BABYLON.Matrix.Identity();
  49943. }
  49944. else {
  49945. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  49946. }
  49947. return _this;
  49948. }
  49949. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  49950. get: function () {
  49951. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  49952. },
  49953. enumerable: true,
  49954. configurable: true
  49955. });
  49956. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  49957. get: function () {
  49958. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  49959. },
  49960. enumerable: true,
  49961. configurable: true
  49962. });
  49963. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  49964. get: function () {
  49965. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  49966. },
  49967. enumerable: true,
  49968. configurable: true
  49969. });
  49970. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  49971. set: function (callback) {
  49972. if (this._onAfterUnbindObserver) {
  49973. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  49974. }
  49975. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  49976. },
  49977. enumerable: true,
  49978. configurable: true
  49979. });
  49980. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  49981. set: function (callback) {
  49982. if (this._onBeforeRenderObserver) {
  49983. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  49984. }
  49985. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  49986. },
  49987. enumerable: true,
  49988. configurable: true
  49989. });
  49990. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  49991. set: function (callback) {
  49992. if (this._onAfterRenderObserver) {
  49993. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  49994. }
  49995. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  49996. },
  49997. enumerable: true,
  49998. configurable: true
  49999. });
  50000. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  50001. set: function (callback) {
  50002. if (this._onClearObserver) {
  50003. this.onClearObservable.remove(this._onClearObserver);
  50004. }
  50005. this._onClearObserver = this.onClearObservable.add(callback);
  50006. },
  50007. enumerable: true,
  50008. configurable: true
  50009. });
  50010. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  50011. get: function () {
  50012. return this._renderTargetOptions;
  50013. },
  50014. enumerable: true,
  50015. configurable: true
  50016. });
  50017. RenderTargetTexture.prototype._onRatioRescale = function () {
  50018. if (this._sizeRatio) {
  50019. this.resize(this._initialSizeParameter);
  50020. }
  50021. };
  50022. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  50023. if (size.ratio) {
  50024. this._sizeRatio = size.ratio;
  50025. this._size = {
  50026. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  50027. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  50028. };
  50029. }
  50030. else {
  50031. this._size = size;
  50032. }
  50033. };
  50034. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  50035. get: function () {
  50036. return this._samples;
  50037. },
  50038. set: function (value) {
  50039. if (this._samples === value) {
  50040. return;
  50041. }
  50042. var scene = this.getScene();
  50043. if (!scene) {
  50044. return;
  50045. }
  50046. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  50047. },
  50048. enumerable: true,
  50049. configurable: true
  50050. });
  50051. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  50052. this._currentRefreshId = -1;
  50053. };
  50054. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  50055. get: function () {
  50056. return this._refreshRate;
  50057. },
  50058. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  50059. set: function (value) {
  50060. this._refreshRate = value;
  50061. this.resetRefreshCounter();
  50062. },
  50063. enumerable: true,
  50064. configurable: true
  50065. });
  50066. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  50067. if (!this._postProcessManager) {
  50068. var scene = this.getScene();
  50069. if (!scene) {
  50070. return;
  50071. }
  50072. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  50073. this._postProcesses = new Array();
  50074. }
  50075. this._postProcesses.push(postProcess);
  50076. this._postProcesses[0].autoClear = false;
  50077. };
  50078. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  50079. if (!this._postProcesses) {
  50080. return;
  50081. }
  50082. if (dispose) {
  50083. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  50084. var postProcess = _a[_i];
  50085. postProcess.dispose();
  50086. }
  50087. }
  50088. this._postProcesses = [];
  50089. };
  50090. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  50091. if (!this._postProcesses) {
  50092. return;
  50093. }
  50094. var index = this._postProcesses.indexOf(postProcess);
  50095. if (index === -1) {
  50096. return;
  50097. }
  50098. this._postProcesses.splice(index, 1);
  50099. if (this._postProcesses.length > 0) {
  50100. this._postProcesses[0].autoClear = false;
  50101. }
  50102. };
  50103. RenderTargetTexture.prototype._shouldRender = function () {
  50104. if (this._currentRefreshId === -1) {
  50105. this._currentRefreshId = 1;
  50106. return true;
  50107. }
  50108. if (this.refreshRate === this._currentRefreshId) {
  50109. this._currentRefreshId = 1;
  50110. return true;
  50111. }
  50112. this._currentRefreshId++;
  50113. return false;
  50114. };
  50115. RenderTargetTexture.prototype.getRenderSize = function () {
  50116. if (this._size.width) {
  50117. return this._size.width;
  50118. }
  50119. return this._size;
  50120. };
  50121. RenderTargetTexture.prototype.getRenderWidth = function () {
  50122. if (this._size.width) {
  50123. return this._size.width;
  50124. }
  50125. return this._size;
  50126. };
  50127. RenderTargetTexture.prototype.getRenderHeight = function () {
  50128. if (this._size.width) {
  50129. return this._size.height;
  50130. }
  50131. return this._size;
  50132. };
  50133. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  50134. get: function () {
  50135. return true;
  50136. },
  50137. enumerable: true,
  50138. configurable: true
  50139. });
  50140. RenderTargetTexture.prototype.scale = function (ratio) {
  50141. var newSize = this.getRenderSize() * ratio;
  50142. this.resize(newSize);
  50143. };
  50144. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  50145. if (this.isCube) {
  50146. return this._textureMatrix;
  50147. }
  50148. return _super.prototype.getReflectionTextureMatrix.call(this);
  50149. };
  50150. RenderTargetTexture.prototype.resize = function (size) {
  50151. this.releaseInternalTexture();
  50152. var scene = this.getScene();
  50153. if (!scene) {
  50154. return;
  50155. }
  50156. this._processSizeParameter(size);
  50157. if (this.isCube) {
  50158. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  50159. }
  50160. else {
  50161. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  50162. }
  50163. };
  50164. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  50165. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  50166. if (dumpForDebug === void 0) { dumpForDebug = false; }
  50167. var scene = this.getScene();
  50168. if (!scene) {
  50169. return;
  50170. }
  50171. var engine = scene.getEngine();
  50172. if (this.useCameraPostProcesses !== undefined) {
  50173. useCameraPostProcess = this.useCameraPostProcesses;
  50174. }
  50175. if (this._waitingRenderList) {
  50176. this.renderList = [];
  50177. for (var index = 0; index < this._waitingRenderList.length; index++) {
  50178. var id = this._waitingRenderList[index];
  50179. var mesh_1 = scene.getMeshByID(id);
  50180. if (mesh_1) {
  50181. this.renderList.push(mesh_1);
  50182. }
  50183. }
  50184. delete this._waitingRenderList;
  50185. }
  50186. // Is predicate defined?
  50187. if (this.renderListPredicate) {
  50188. if (this.renderList) {
  50189. this.renderList.splice(0); // Clear previous renderList
  50190. }
  50191. else {
  50192. this.renderList = [];
  50193. }
  50194. var scene = this.getScene();
  50195. if (!scene) {
  50196. return;
  50197. }
  50198. var sceneMeshes = scene.meshes;
  50199. for (var index = 0; index < sceneMeshes.length; index++) {
  50200. var mesh = sceneMeshes[index];
  50201. if (this.renderListPredicate(mesh)) {
  50202. this.renderList.push(mesh);
  50203. }
  50204. }
  50205. }
  50206. this.onBeforeBindObservable.notifyObservers(this);
  50207. // Set custom projection.
  50208. // Needs to be before binding to prevent changing the aspect ratio.
  50209. var camera;
  50210. if (this.activeCamera) {
  50211. camera = this.activeCamera;
  50212. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  50213. if (this.activeCamera !== scene.activeCamera) {
  50214. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  50215. }
  50216. }
  50217. else {
  50218. camera = scene.activeCamera;
  50219. if (camera) {
  50220. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  50221. }
  50222. }
  50223. // Prepare renderingManager
  50224. this._renderingManager.reset();
  50225. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  50226. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  50227. var sceneRenderId = scene.getRenderId();
  50228. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  50229. var mesh = currentRenderList[meshIndex];
  50230. if (mesh) {
  50231. if (!mesh.isReady()) {
  50232. // Reset _currentRefreshId
  50233. this.resetRefreshCounter();
  50234. continue;
  50235. }
  50236. mesh._preActivateForIntermediateRendering(sceneRenderId);
  50237. var isMasked = void 0;
  50238. if (!this.renderList && camera) {
  50239. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  50240. }
  50241. else {
  50242. isMasked = false;
  50243. }
  50244. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  50245. mesh._activate(sceneRenderId);
  50246. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  50247. var subMesh = mesh.subMeshes[subIndex];
  50248. scene._activeIndices.addCount(subMesh.indexCount, false);
  50249. this._renderingManager.dispatch(subMesh);
  50250. }
  50251. }
  50252. }
  50253. }
  50254. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  50255. var particleSystem = scene.particleSystems[particleIndex];
  50256. var emitter = particleSystem.emitter;
  50257. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  50258. continue;
  50259. }
  50260. if (currentRenderList.indexOf(emitter) >= 0) {
  50261. this._renderingManager.dispatchParticles(particleSystem);
  50262. }
  50263. }
  50264. if (this.isCube) {
  50265. for (var face = 0; face < 6; face++) {
  50266. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  50267. scene.incrementRenderId();
  50268. scene.resetCachedMaterial();
  50269. }
  50270. }
  50271. else {
  50272. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  50273. }
  50274. this.onAfterUnbindObservable.notifyObservers(this);
  50275. if (scene.activeCamera) {
  50276. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  50277. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  50278. }
  50279. engine.setViewport(scene.activeCamera.viewport);
  50280. }
  50281. scene.resetCachedMaterial();
  50282. };
  50283. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  50284. var minimum = 128;
  50285. var x = renderDimension * scale;
  50286. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  50287. // Ensure we don't exceed the render dimension (while staying POT)
  50288. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  50289. };
  50290. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  50291. var _this = this;
  50292. var scene = this.getScene();
  50293. if (!scene) {
  50294. return;
  50295. }
  50296. var engine = scene.getEngine();
  50297. if (!this._texture) {
  50298. return;
  50299. }
  50300. // Bind
  50301. if (this._postProcessManager) {
  50302. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  50303. }
  50304. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  50305. if (this._texture) {
  50306. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  50307. }
  50308. }
  50309. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  50310. // Clear
  50311. if (this.onClearObservable.hasObservers()) {
  50312. this.onClearObservable.notifyObservers(engine);
  50313. }
  50314. else {
  50315. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  50316. }
  50317. if (!this._doNotChangeAspectRatio) {
  50318. scene.updateTransformMatrix(true);
  50319. }
  50320. // Render
  50321. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  50322. if (this._postProcessManager) {
  50323. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  50324. }
  50325. else if (useCameraPostProcess) {
  50326. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  50327. }
  50328. if (!this._doNotChangeAspectRatio) {
  50329. scene.updateTransformMatrix(true);
  50330. }
  50331. // Dump ?
  50332. if (dumpForDebug) {
  50333. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  50334. }
  50335. // Unbind
  50336. if (!this.isCube || faceIndex === 5) {
  50337. if (this.isCube) {
  50338. if (faceIndex === 5) {
  50339. engine.generateMipMapsForCubemap(this._texture);
  50340. }
  50341. }
  50342. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  50343. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  50344. });
  50345. }
  50346. else {
  50347. this.onAfterRenderObservable.notifyObservers(faceIndex);
  50348. }
  50349. };
  50350. /**
  50351. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  50352. * This allowed control for front to back rendering or reversly depending of the special needs.
  50353. *
  50354. * @param renderingGroupId The rendering group id corresponding to its index
  50355. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  50356. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  50357. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  50358. */
  50359. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  50360. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  50361. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  50362. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  50363. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  50364. };
  50365. /**
  50366. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  50367. *
  50368. * @param renderingGroupId The rendering group id corresponding to its index
  50369. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  50370. */
  50371. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  50372. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  50373. };
  50374. RenderTargetTexture.prototype.clone = function () {
  50375. var textureSize = this.getSize();
  50376. 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);
  50377. // Base texture
  50378. newTexture.hasAlpha = this.hasAlpha;
  50379. newTexture.level = this.level;
  50380. // RenderTarget Texture
  50381. newTexture.coordinatesMode = this.coordinatesMode;
  50382. if (this.renderList) {
  50383. newTexture.renderList = this.renderList.slice(0);
  50384. }
  50385. return newTexture;
  50386. };
  50387. RenderTargetTexture.prototype.serialize = function () {
  50388. if (!this.name) {
  50389. return null;
  50390. }
  50391. var serializationObject = _super.prototype.serialize.call(this);
  50392. serializationObject.renderTargetSize = this.getRenderSize();
  50393. serializationObject.renderList = [];
  50394. if (this.renderList) {
  50395. for (var index = 0; index < this.renderList.length; index++) {
  50396. serializationObject.renderList.push(this.renderList[index].id);
  50397. }
  50398. }
  50399. return serializationObject;
  50400. };
  50401. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  50402. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  50403. var objBuffer = this.getInternalTexture();
  50404. var scene = this.getScene();
  50405. if (objBuffer && scene) {
  50406. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  50407. }
  50408. };
  50409. RenderTargetTexture.prototype.dispose = function () {
  50410. if (this._postProcessManager) {
  50411. this._postProcessManager.dispose();
  50412. this._postProcessManager = null;
  50413. }
  50414. this.clearPostProcesses(true);
  50415. if (this._resizeObserver) {
  50416. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  50417. this._resizeObserver = null;
  50418. }
  50419. this.renderList = null;
  50420. // Remove from custom render targets
  50421. var scene = this.getScene();
  50422. if (!scene) {
  50423. return;
  50424. }
  50425. var index = scene.customRenderTargets.indexOf(this);
  50426. if (index >= 0) {
  50427. scene.customRenderTargets.splice(index, 1);
  50428. }
  50429. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  50430. var camera = _a[_i];
  50431. index = camera.customRenderTargets.indexOf(this);
  50432. if (index >= 0) {
  50433. camera.customRenderTargets.splice(index, 1);
  50434. }
  50435. }
  50436. _super.prototype.dispose.call(this);
  50437. };
  50438. RenderTargetTexture.prototype._rebuild = function () {
  50439. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  50440. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  50441. }
  50442. if (this._postProcessManager) {
  50443. this._postProcessManager._rebuild();
  50444. }
  50445. };
  50446. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  50447. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  50448. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  50449. return RenderTargetTexture;
  50450. }(BABYLON.Texture));
  50451. BABYLON.RenderTargetTexture = RenderTargetTexture;
  50452. })(BABYLON || (BABYLON = {}));
  50453. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  50454. var BABYLON;
  50455. (function (BABYLON) {
  50456. ;
  50457. var MultiRenderTarget = /** @class */ (function (_super) {
  50458. __extends(MultiRenderTarget, _super);
  50459. function MultiRenderTarget(name, size, count, scene, options) {
  50460. var _this = this;
  50461. options = options || {};
  50462. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  50463. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  50464. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  50465. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  50466. _this._engine = scene.getEngine();
  50467. if (!_this.isSupported) {
  50468. _this.dispose();
  50469. return;
  50470. }
  50471. var types = [];
  50472. var samplingModes = [];
  50473. for (var i = 0; i < count; i++) {
  50474. if (options.types && options.types[i]) {
  50475. types.push(options.types[i]);
  50476. }
  50477. else {
  50478. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  50479. }
  50480. if (options.samplingModes && options.samplingModes[i]) {
  50481. samplingModes.push(options.samplingModes[i]);
  50482. }
  50483. else {
  50484. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  50485. }
  50486. }
  50487. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  50488. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  50489. _this._size = size;
  50490. _this._multiRenderTargetOptions = {
  50491. samplingModes: samplingModes,
  50492. generateMipMaps: generateMipMaps,
  50493. generateDepthBuffer: generateDepthBuffer,
  50494. generateStencilBuffer: generateStencilBuffer,
  50495. generateDepthTexture: generateDepthTexture,
  50496. types: types,
  50497. textureCount: count
  50498. };
  50499. _this._createInternalTextures();
  50500. _this._createTextures();
  50501. return _this;
  50502. }
  50503. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  50504. get: function () {
  50505. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  50506. },
  50507. enumerable: true,
  50508. configurable: true
  50509. });
  50510. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  50511. get: function () {
  50512. return this._textures;
  50513. },
  50514. enumerable: true,
  50515. configurable: true
  50516. });
  50517. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  50518. get: function () {
  50519. return this._textures[this._textures.length - 1];
  50520. },
  50521. enumerable: true,
  50522. configurable: true
  50523. });
  50524. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  50525. set: function (wrap) {
  50526. if (this._textures) {
  50527. for (var i = 0; i < this._textures.length; i++) {
  50528. this._textures[i].wrapU = wrap;
  50529. }
  50530. }
  50531. },
  50532. enumerable: true,
  50533. configurable: true
  50534. });
  50535. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  50536. set: function (wrap) {
  50537. if (this._textures) {
  50538. for (var i = 0; i < this._textures.length; i++) {
  50539. this._textures[i].wrapV = wrap;
  50540. }
  50541. }
  50542. },
  50543. enumerable: true,
  50544. configurable: true
  50545. });
  50546. MultiRenderTarget.prototype._rebuild = function () {
  50547. this.releaseInternalTextures();
  50548. this._createInternalTextures();
  50549. for (var i = 0; i < this._internalTextures.length; i++) {
  50550. var texture = this._textures[i];
  50551. texture._texture = this._internalTextures[i];
  50552. }
  50553. // Keeps references to frame buffer and stencil/depth buffer
  50554. this._texture = this._internalTextures[0];
  50555. };
  50556. MultiRenderTarget.prototype._createInternalTextures = function () {
  50557. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  50558. };
  50559. MultiRenderTarget.prototype._createTextures = function () {
  50560. this._textures = [];
  50561. for (var i = 0; i < this._internalTextures.length; i++) {
  50562. var texture = new BABYLON.Texture(null, this.getScene());
  50563. texture._texture = this._internalTextures[i];
  50564. this._textures.push(texture);
  50565. }
  50566. // Keeps references to frame buffer and stencil/depth buffer
  50567. this._texture = this._internalTextures[0];
  50568. };
  50569. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  50570. get: function () {
  50571. return this._samples;
  50572. },
  50573. set: function (value) {
  50574. if (this._samples === value) {
  50575. return;
  50576. }
  50577. for (var i = 0; i < this._internalTextures.length; i++) {
  50578. this._samples = this._engine.updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  50579. }
  50580. },
  50581. enumerable: true,
  50582. configurable: true
  50583. });
  50584. MultiRenderTarget.prototype.resize = function (size) {
  50585. this.releaseInternalTextures();
  50586. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  50587. this._createInternalTextures();
  50588. };
  50589. MultiRenderTarget.prototype.dispose = function () {
  50590. this.releaseInternalTextures();
  50591. _super.prototype.dispose.call(this);
  50592. };
  50593. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  50594. if (!this._internalTextures) {
  50595. return;
  50596. }
  50597. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  50598. if (this._internalTextures[i] !== undefined) {
  50599. this._internalTextures[i].dispose();
  50600. this._internalTextures.splice(i, 1);
  50601. }
  50602. }
  50603. };
  50604. return MultiRenderTarget;
  50605. }(BABYLON.RenderTargetTexture));
  50606. BABYLON.MultiRenderTarget = MultiRenderTarget;
  50607. })(BABYLON || (BABYLON = {}));
  50608. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  50609. var BABYLON;
  50610. (function (BABYLON) {
  50611. var MirrorTexture = /** @class */ (function (_super) {
  50612. __extends(MirrorTexture, _super);
  50613. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  50614. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50615. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  50616. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  50617. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  50618. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  50619. _this._transformMatrix = BABYLON.Matrix.Zero();
  50620. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  50621. _this._adaptiveBlurKernel = 0;
  50622. _this._blurKernelX = 0;
  50623. _this._blurKernelY = 0;
  50624. _this._blurRatio = 1.0;
  50625. _this.ignoreCameraViewport = true;
  50626. _this.onBeforeRenderObservable.add(function () {
  50627. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  50628. _this._savedViewMatrix = scene.getViewMatrix();
  50629. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  50630. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  50631. scene.clipPlane = _this.mirrorPlane;
  50632. scene.getEngine().cullBackFaces = false;
  50633. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  50634. });
  50635. _this.onAfterRenderObservable.add(function () {
  50636. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  50637. scene.getEngine().cullBackFaces = true;
  50638. scene._mirroredCameraPosition = null;
  50639. delete scene.clipPlane;
  50640. });
  50641. return _this;
  50642. }
  50643. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  50644. get: function () {
  50645. return this._blurRatio;
  50646. },
  50647. set: function (value) {
  50648. if (this._blurRatio === value) {
  50649. return;
  50650. }
  50651. this._blurRatio = value;
  50652. this._preparePostProcesses();
  50653. },
  50654. enumerable: true,
  50655. configurable: true
  50656. });
  50657. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  50658. set: function (value) {
  50659. this._adaptiveBlurKernel = value;
  50660. this._autoComputeBlurKernel();
  50661. },
  50662. enumerable: true,
  50663. configurable: true
  50664. });
  50665. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  50666. set: function (value) {
  50667. this.blurKernelX = value;
  50668. this.blurKernelY = value;
  50669. },
  50670. enumerable: true,
  50671. configurable: true
  50672. });
  50673. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  50674. get: function () {
  50675. return this._blurKernelX;
  50676. },
  50677. set: function (value) {
  50678. if (this._blurKernelX === value) {
  50679. return;
  50680. }
  50681. this._blurKernelX = value;
  50682. this._preparePostProcesses();
  50683. },
  50684. enumerable: true,
  50685. configurable: true
  50686. });
  50687. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  50688. get: function () {
  50689. return this._blurKernelY;
  50690. },
  50691. set: function (value) {
  50692. if (this._blurKernelY === value) {
  50693. return;
  50694. }
  50695. this._blurKernelY = value;
  50696. this._preparePostProcesses();
  50697. },
  50698. enumerable: true,
  50699. configurable: true
  50700. });
  50701. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  50702. var engine = this.getScene().getEngine();
  50703. var dw = this.getRenderWidth() / engine.getRenderWidth();
  50704. var dh = this.getRenderHeight() / engine.getRenderHeight();
  50705. this.blurKernelX = this._adaptiveBlurKernel * dw;
  50706. this.blurKernelY = this._adaptiveBlurKernel * dh;
  50707. };
  50708. MirrorTexture.prototype._onRatioRescale = function () {
  50709. if (this._sizeRatio) {
  50710. this.resize(this._initialSizeParameter);
  50711. if (!this._adaptiveBlurKernel) {
  50712. this._preparePostProcesses();
  50713. }
  50714. }
  50715. if (this._adaptiveBlurKernel) {
  50716. this._autoComputeBlurKernel();
  50717. }
  50718. };
  50719. MirrorTexture.prototype._preparePostProcesses = function () {
  50720. this.clearPostProcesses(true);
  50721. if (this._blurKernelX && this._blurKernelY) {
  50722. var engine = this.getScene().getEngine();
  50723. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50724. 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);
  50725. this._blurX.autoClear = false;
  50726. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  50727. this._blurX.outputTexture = this._texture;
  50728. }
  50729. else {
  50730. this._blurX.alwaysForcePOT = true;
  50731. }
  50732. 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);
  50733. this._blurY.autoClear = false;
  50734. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  50735. this.addPostProcess(this._blurX);
  50736. this.addPostProcess(this._blurY);
  50737. }
  50738. else {
  50739. if (this._blurY) {
  50740. this.removePostProcess(this._blurY);
  50741. this._blurY.dispose();
  50742. this._blurY = null;
  50743. }
  50744. if (this._blurX) {
  50745. this.removePostProcess(this._blurX);
  50746. this._blurX.dispose();
  50747. this._blurX = null;
  50748. }
  50749. }
  50750. };
  50751. MirrorTexture.prototype.clone = function () {
  50752. var scene = this.getScene();
  50753. if (!scene) {
  50754. return this;
  50755. }
  50756. var textureSize = this.getSize();
  50757. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  50758. // Base texture
  50759. newTexture.hasAlpha = this.hasAlpha;
  50760. newTexture.level = this.level;
  50761. // Mirror Texture
  50762. newTexture.mirrorPlane = this.mirrorPlane.clone();
  50763. if (this.renderList) {
  50764. newTexture.renderList = this.renderList.slice(0);
  50765. }
  50766. return newTexture;
  50767. };
  50768. MirrorTexture.prototype.serialize = function () {
  50769. if (!this.name) {
  50770. return null;
  50771. }
  50772. var serializationObject = _super.prototype.serialize.call(this);
  50773. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  50774. return serializationObject;
  50775. };
  50776. return MirrorTexture;
  50777. }(BABYLON.RenderTargetTexture));
  50778. BABYLON.MirrorTexture = MirrorTexture;
  50779. })(BABYLON || (BABYLON = {}));
  50780. //# sourceMappingURL=babylon.mirrorTexture.js.map
  50781. var BABYLON;
  50782. (function (BABYLON) {
  50783. /**
  50784. * Creates a refraction texture used by refraction channel of the standard material.
  50785. * @param name the texture name
  50786. * @param size size of the underlying texture
  50787. * @param scene root scene
  50788. */
  50789. var RefractionTexture = /** @class */ (function (_super) {
  50790. __extends(RefractionTexture, _super);
  50791. function RefractionTexture(name, size, scene, generateMipMaps) {
  50792. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  50793. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  50794. _this.depth = 2.0;
  50795. _this.onBeforeRenderObservable.add(function () {
  50796. scene.clipPlane = _this.refractionPlane;
  50797. });
  50798. _this.onAfterRenderObservable.add(function () {
  50799. delete scene.clipPlane;
  50800. });
  50801. return _this;
  50802. }
  50803. RefractionTexture.prototype.clone = function () {
  50804. var scene = this.getScene();
  50805. if (!scene) {
  50806. return this;
  50807. }
  50808. var textureSize = this.getSize();
  50809. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  50810. // Base texture
  50811. newTexture.hasAlpha = this.hasAlpha;
  50812. newTexture.level = this.level;
  50813. // Refraction Texture
  50814. newTexture.refractionPlane = this.refractionPlane.clone();
  50815. if (this.renderList) {
  50816. newTexture.renderList = this.renderList.slice(0);
  50817. }
  50818. newTexture.depth = this.depth;
  50819. return newTexture;
  50820. };
  50821. RefractionTexture.prototype.serialize = function () {
  50822. if (!this.name) {
  50823. return null;
  50824. }
  50825. var serializationObject = _super.prototype.serialize.call(this);
  50826. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  50827. serializationObject.depth = this.depth;
  50828. return serializationObject;
  50829. };
  50830. return RefractionTexture;
  50831. }(BABYLON.RenderTargetTexture));
  50832. BABYLON.RefractionTexture = RefractionTexture;
  50833. })(BABYLON || (BABYLON = {}));
  50834. //# sourceMappingURL=babylon.refractionTexture.js.map
  50835. var BABYLON;
  50836. (function (BABYLON) {
  50837. var DynamicTexture = /** @class */ (function (_super) {
  50838. __extends(DynamicTexture, _super);
  50839. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  50840. if (scene === void 0) { scene = null; }
  50841. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50842. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  50843. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  50844. _this.name = name;
  50845. _this._engine = _this.getScene().getEngine();
  50846. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50847. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50848. _this._generateMipMaps = generateMipMaps;
  50849. if (options.getContext) {
  50850. _this._canvas = options;
  50851. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  50852. }
  50853. else {
  50854. _this._canvas = document.createElement("canvas");
  50855. if (options.width) {
  50856. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  50857. }
  50858. else {
  50859. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  50860. }
  50861. }
  50862. var textureSize = _this.getSize();
  50863. _this._canvas.width = textureSize.width;
  50864. _this._canvas.height = textureSize.height;
  50865. _this._context = _this._canvas.getContext("2d");
  50866. return _this;
  50867. }
  50868. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  50869. get: function () {
  50870. return true;
  50871. },
  50872. enumerable: true,
  50873. configurable: true
  50874. });
  50875. DynamicTexture.prototype._recreate = function (textureSize) {
  50876. this._canvas.width = textureSize.width;
  50877. this._canvas.height = textureSize.height;
  50878. this.releaseInternalTexture();
  50879. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  50880. };
  50881. DynamicTexture.prototype.scale = function (ratio) {
  50882. var textureSize = this.getSize();
  50883. textureSize.width *= ratio;
  50884. textureSize.height *= ratio;
  50885. this._recreate(textureSize);
  50886. };
  50887. DynamicTexture.prototype.scaleTo = function (width, height) {
  50888. var textureSize = this.getSize();
  50889. textureSize.width = width;
  50890. textureSize.height = height;
  50891. this._recreate(textureSize);
  50892. };
  50893. DynamicTexture.prototype.getContext = function () {
  50894. return this._context;
  50895. };
  50896. DynamicTexture.prototype.clear = function () {
  50897. var size = this.getSize();
  50898. this._context.fillRect(0, 0, size.width, size.height);
  50899. };
  50900. DynamicTexture.prototype.update = function (invertY) {
  50901. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  50902. };
  50903. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  50904. if (update === void 0) { update = true; }
  50905. var size = this.getSize();
  50906. if (clearColor) {
  50907. this._context.fillStyle = clearColor;
  50908. this._context.fillRect(0, 0, size.width, size.height);
  50909. }
  50910. this._context.font = font;
  50911. if (x === null || x === undefined) {
  50912. var textSize = this._context.measureText(text);
  50913. x = (size.width - textSize.width) / 2;
  50914. }
  50915. if (y === null || y === undefined) {
  50916. var fontSize = parseInt((font.replace(/\D/g, '')));
  50917. ;
  50918. y = (size.height / 2) + (fontSize / 3.65);
  50919. }
  50920. this._context.fillStyle = color;
  50921. this._context.fillText(text, x, y);
  50922. if (update) {
  50923. this.update(invertY);
  50924. }
  50925. };
  50926. DynamicTexture.prototype.clone = function () {
  50927. var scene = this.getScene();
  50928. if (!scene) {
  50929. return this;
  50930. }
  50931. var textureSize = this.getSize();
  50932. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  50933. // Base texture
  50934. newTexture.hasAlpha = this.hasAlpha;
  50935. newTexture.level = this.level;
  50936. // Dynamic Texture
  50937. newTexture.wrapU = this.wrapU;
  50938. newTexture.wrapV = this.wrapV;
  50939. return newTexture;
  50940. };
  50941. DynamicTexture.prototype._rebuild = function () {
  50942. this.update();
  50943. };
  50944. return DynamicTexture;
  50945. }(BABYLON.Texture));
  50946. BABYLON.DynamicTexture = DynamicTexture;
  50947. })(BABYLON || (BABYLON = {}));
  50948. //# sourceMappingURL=babylon.dynamicTexture.js.map
  50949. var BABYLON;
  50950. (function (BABYLON) {
  50951. var VideoTexture = /** @class */ (function (_super) {
  50952. __extends(VideoTexture, _super);
  50953. /**
  50954. * Creates a video texture.
  50955. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  50956. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  50957. * @param {BABYLON.Scene} scene is obviously the current scene.
  50958. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  50959. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  50960. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  50961. */
  50962. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  50963. if (generateMipMaps === void 0) { generateMipMaps = false; }
  50964. if (invertY === void 0) { invertY = false; }
  50965. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50966. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  50967. _this._autoLaunch = true;
  50968. var urls = null;
  50969. _this.name = name;
  50970. if (urlsOrVideo instanceof HTMLVideoElement) {
  50971. _this.video = urlsOrVideo;
  50972. }
  50973. else {
  50974. urls = urlsOrVideo;
  50975. _this.video = document.createElement("video");
  50976. _this.video.autoplay = false;
  50977. _this.video.loop = true;
  50978. }
  50979. _this._engine = _this.getScene().getEngine();
  50980. _this._generateMipMaps = generateMipMaps;
  50981. _this._samplingMode = samplingMode;
  50982. if (!_this._engine.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  50983. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  50984. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  50985. }
  50986. else {
  50987. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50988. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50989. _this._generateMipMaps = false;
  50990. }
  50991. if (urls) {
  50992. _this.video.addEventListener("canplay", function () {
  50993. _this._createTexture();
  50994. });
  50995. urls.forEach(function (url) {
  50996. var source = document.createElement("source");
  50997. source.src = url;
  50998. _this.video.appendChild(source);
  50999. });
  51000. }
  51001. else {
  51002. _this._createTexture();
  51003. }
  51004. _this._lastUpdate = BABYLON.Tools.Now;
  51005. return _this;
  51006. }
  51007. VideoTexture.prototype.__setTextureReady = function () {
  51008. if (this._texture) {
  51009. this._texture.isReady = true;
  51010. }
  51011. };
  51012. VideoTexture.prototype._createTexture = function () {
  51013. this._texture = this._engine.createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  51014. if (this._autoLaunch) {
  51015. this._autoLaunch = false;
  51016. this.video.play();
  51017. }
  51018. this._setTextureReady = this.__setTextureReady.bind(this);
  51019. this.video.addEventListener("playing", this._setTextureReady);
  51020. };
  51021. VideoTexture.prototype._rebuild = function () {
  51022. this.update();
  51023. };
  51024. VideoTexture.prototype.update = function () {
  51025. var now = BABYLON.Tools.Now;
  51026. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  51027. return false;
  51028. }
  51029. this._lastUpdate = now;
  51030. this._engine.updateVideoTexture(this._texture, this.video, this._invertY);
  51031. return true;
  51032. };
  51033. VideoTexture.prototype.dispose = function () {
  51034. _super.prototype.dispose.call(this);
  51035. this.video.removeEventListener("playing", this._setTextureReady);
  51036. };
  51037. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  51038. var video = document.createElement("video");
  51039. var constraintsDeviceId;
  51040. if (constraints && constraints.deviceId) {
  51041. constraintsDeviceId = {
  51042. exact: constraints.deviceId
  51043. };
  51044. }
  51045. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  51046. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  51047. if (navigator.getUserMedia) {
  51048. navigator.getUserMedia({
  51049. video: {
  51050. deviceId: constraintsDeviceId,
  51051. width: {
  51052. min: (constraints && constraints.minWidth) || 256,
  51053. max: (constraints && constraints.maxWidth) || 640
  51054. },
  51055. height: {
  51056. min: (constraints && constraints.minHeight) || 256,
  51057. max: (constraints && constraints.maxHeight) || 480
  51058. }
  51059. }
  51060. }, function (stream) {
  51061. if (video.mozSrcObject !== undefined) {
  51062. video.mozSrcObject = stream;
  51063. }
  51064. else {
  51065. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  51066. }
  51067. video.play();
  51068. if (onReady) {
  51069. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  51070. }
  51071. }, function (e) {
  51072. BABYLON.Tools.Error(e.name);
  51073. });
  51074. }
  51075. };
  51076. return VideoTexture;
  51077. }(BABYLON.Texture));
  51078. BABYLON.VideoTexture = VideoTexture;
  51079. })(BABYLON || (BABYLON = {}));
  51080. //# sourceMappingURL=babylon.videoTexture.js.map
  51081. var BABYLON;
  51082. (function (BABYLON) {
  51083. var RawTexture = /** @class */ (function (_super) {
  51084. __extends(RawTexture, _super);
  51085. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  51086. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51087. if (invertY === void 0) { invertY = false; }
  51088. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51089. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  51090. _this.format = format;
  51091. _this._engine = scene.getEngine();
  51092. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  51093. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51094. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51095. return _this;
  51096. }
  51097. RawTexture.prototype.update = function (data) {
  51098. this._engine.updateRawTexture(this._texture, data, this.format, this._invertY);
  51099. };
  51100. // Statics
  51101. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51102. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51103. if (invertY === void 0) { invertY = false; }
  51104. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51105. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  51106. };
  51107. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51108. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51109. if (invertY === void 0) { invertY = false; }
  51110. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51111. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  51112. };
  51113. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51114. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51115. if (invertY === void 0) { invertY = false; }
  51116. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51117. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  51118. };
  51119. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51120. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51121. if (invertY === void 0) { invertY = false; }
  51122. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51123. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  51124. };
  51125. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51126. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51127. if (invertY === void 0) { invertY = false; }
  51128. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51129. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  51130. };
  51131. return RawTexture;
  51132. }(BABYLON.Texture));
  51133. BABYLON.RawTexture = RawTexture;
  51134. })(BABYLON || (BABYLON = {}));
  51135. //# sourceMappingURL=babylon.rawTexture.js.map
  51136. var BABYLON;
  51137. (function (BABYLON) {
  51138. var PostProcess = /** @class */ (function () {
  51139. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  51140. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  51141. if (defines === void 0) { defines = null; }
  51142. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51143. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  51144. if (blockCompilation === void 0) { blockCompilation = false; }
  51145. this.name = name;
  51146. this.width = -1;
  51147. this.height = -1;
  51148. this.autoClear = true;
  51149. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  51150. this.animations = new Array();
  51151. /*
  51152. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  51153. Can only be used on a single postprocess or on the last one of a chain.
  51154. */
  51155. this.enablePixelPerfectMode = false;
  51156. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  51157. this.alwaysForcePOT = false;
  51158. this.samples = 1;
  51159. this.adaptScaleToCurrentViewport = false;
  51160. this._reusable = false;
  51161. this._textures = new BABYLON.SmartArray(2);
  51162. this._currentRenderTextureInd = 0;
  51163. this._scaleRatio = new BABYLON.Vector2(1, 1);
  51164. this._texelSize = BABYLON.Vector2.Zero();
  51165. // Events
  51166. /**
  51167. * An event triggered when the postprocess is activated.
  51168. * @type {BABYLON.Observable}
  51169. */
  51170. this.onActivateObservable = new BABYLON.Observable();
  51171. /**
  51172. * An event triggered when the postprocess changes its size.
  51173. * @type {BABYLON.Observable}
  51174. */
  51175. this.onSizeChangedObservable = new BABYLON.Observable();
  51176. /**
  51177. * An event triggered when the postprocess applies its effect.
  51178. * @type {BABYLON.Observable}
  51179. */
  51180. this.onApplyObservable = new BABYLON.Observable();
  51181. /**
  51182. * An event triggered before rendering the postprocess
  51183. * @type {BABYLON.Observable}
  51184. */
  51185. this.onBeforeRenderObservable = new BABYLON.Observable();
  51186. /**
  51187. * An event triggered after rendering the postprocess
  51188. * @type {BABYLON.Observable}
  51189. */
  51190. this.onAfterRenderObservable = new BABYLON.Observable();
  51191. if (camera != null) {
  51192. this._camera = camera;
  51193. this._scene = camera.getScene();
  51194. camera.attachPostProcess(this);
  51195. this._engine = this._scene.getEngine();
  51196. this._scene.postProcesses.push(this);
  51197. }
  51198. else if (engine) {
  51199. this._engine = engine;
  51200. this._engine.postProcesses.push(this);
  51201. }
  51202. this._options = options;
  51203. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  51204. this._reusable = reusable || false;
  51205. this._textureType = textureType;
  51206. this._samplers = samplers || [];
  51207. this._samplers.push("textureSampler");
  51208. this._fragmentUrl = fragmentUrl;
  51209. this._vertexUrl = vertexUrl;
  51210. this._parameters = parameters || [];
  51211. this._parameters.push("scale");
  51212. this._indexParameters = indexParameters;
  51213. if (!blockCompilation) {
  51214. this.updateEffect(defines);
  51215. }
  51216. }
  51217. Object.defineProperty(PostProcess.prototype, "onActivate", {
  51218. set: function (callback) {
  51219. if (this._onActivateObserver) {
  51220. this.onActivateObservable.remove(this._onActivateObserver);
  51221. }
  51222. if (callback) {
  51223. this._onActivateObserver = this.onActivateObservable.add(callback);
  51224. }
  51225. },
  51226. enumerable: true,
  51227. configurable: true
  51228. });
  51229. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  51230. set: function (callback) {
  51231. if (this._onSizeChangedObserver) {
  51232. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  51233. }
  51234. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  51235. },
  51236. enumerable: true,
  51237. configurable: true
  51238. });
  51239. Object.defineProperty(PostProcess.prototype, "onApply", {
  51240. set: function (callback) {
  51241. if (this._onApplyObserver) {
  51242. this.onApplyObservable.remove(this._onApplyObserver);
  51243. }
  51244. this._onApplyObserver = this.onApplyObservable.add(callback);
  51245. },
  51246. enumerable: true,
  51247. configurable: true
  51248. });
  51249. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  51250. set: function (callback) {
  51251. if (this._onBeforeRenderObserver) {
  51252. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  51253. }
  51254. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  51255. },
  51256. enumerable: true,
  51257. configurable: true
  51258. });
  51259. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  51260. set: function (callback) {
  51261. if (this._onAfterRenderObserver) {
  51262. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  51263. }
  51264. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  51265. },
  51266. enumerable: true,
  51267. configurable: true
  51268. });
  51269. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  51270. get: function () {
  51271. return this._textures.data[this._currentRenderTextureInd];
  51272. },
  51273. set: function (value) {
  51274. this._forcedOutputTexture = value;
  51275. },
  51276. enumerable: true,
  51277. configurable: true
  51278. });
  51279. PostProcess.prototype.getCamera = function () {
  51280. return this._camera;
  51281. };
  51282. Object.defineProperty(PostProcess.prototype, "texelSize", {
  51283. get: function () {
  51284. if (this._shareOutputWithPostProcess) {
  51285. return this._shareOutputWithPostProcess.texelSize;
  51286. }
  51287. if (this._forcedOutputTexture) {
  51288. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  51289. }
  51290. return this._texelSize;
  51291. },
  51292. enumerable: true,
  51293. configurable: true
  51294. });
  51295. PostProcess.prototype.getEngine = function () {
  51296. return this._engine;
  51297. };
  51298. PostProcess.prototype.getEffect = function () {
  51299. return this._effect;
  51300. };
  51301. PostProcess.prototype.shareOutputWith = function (postProcess) {
  51302. this._disposeTextures();
  51303. this._shareOutputWithPostProcess = postProcess;
  51304. return this;
  51305. };
  51306. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  51307. if (defines === void 0) { defines = null; }
  51308. if (uniforms === void 0) { uniforms = null; }
  51309. if (samplers === void 0) { samplers = null; }
  51310. 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);
  51311. };
  51312. PostProcess.prototype.isReusable = function () {
  51313. return this._reusable;
  51314. };
  51315. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  51316. PostProcess.prototype.markTextureDirty = function () {
  51317. this.width = -1;
  51318. };
  51319. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  51320. var _this = this;
  51321. if (sourceTexture === void 0) { sourceTexture = null; }
  51322. camera = camera || this._camera;
  51323. var scene = camera.getScene();
  51324. var engine = scene.getEngine();
  51325. var maxSize = engine.getCaps().maxTextureSize;
  51326. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  51327. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  51328. var desiredWidth = (this._options.width || requiredWidth);
  51329. var desiredHeight = this._options.height || requiredHeight;
  51330. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  51331. if (this.adaptScaleToCurrentViewport) {
  51332. var currentViewport = engine.currentViewport;
  51333. if (currentViewport) {
  51334. desiredWidth *= currentViewport.width;
  51335. desiredHeight *= currentViewport.height;
  51336. }
  51337. }
  51338. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  51339. if (!this._options.width) {
  51340. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  51341. }
  51342. if (!this._options.height) {
  51343. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  51344. }
  51345. }
  51346. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  51347. if (this._textures.length > 0) {
  51348. for (var i = 0; i < this._textures.length; i++) {
  51349. this._engine._releaseTexture(this._textures.data[i]);
  51350. }
  51351. this._textures.reset();
  51352. }
  51353. this.width = desiredWidth;
  51354. this.height = desiredHeight;
  51355. var textureSize = { width: this.width, height: this.height };
  51356. var textureOptions = {
  51357. generateMipMaps: false,
  51358. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  51359. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  51360. samplingMode: this.renderTargetSamplingMode,
  51361. type: this._textureType
  51362. };
  51363. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  51364. if (this._reusable) {
  51365. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  51366. }
  51367. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  51368. this.onSizeChangedObservable.notifyObservers(this);
  51369. }
  51370. this._textures.forEach(function (texture) {
  51371. if (texture.samples !== _this.samples) {
  51372. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  51373. }
  51374. });
  51375. }
  51376. var target;
  51377. if (this._shareOutputWithPostProcess) {
  51378. target = this._shareOutputWithPostProcess.outputTexture;
  51379. }
  51380. else if (this._forcedOutputTexture) {
  51381. target = this._forcedOutputTexture;
  51382. this.width = this._forcedOutputTexture.width;
  51383. this.height = this._forcedOutputTexture.height;
  51384. }
  51385. else {
  51386. target = this.outputTexture;
  51387. }
  51388. if (this.enablePixelPerfectMode) {
  51389. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  51390. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  51391. }
  51392. else {
  51393. this._scaleRatio.copyFromFloats(1, 1);
  51394. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  51395. }
  51396. this.onActivateObservable.notifyObservers(camera);
  51397. // Clear
  51398. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  51399. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  51400. }
  51401. if (this._reusable) {
  51402. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  51403. }
  51404. };
  51405. Object.defineProperty(PostProcess.prototype, "isSupported", {
  51406. get: function () {
  51407. return this._effect.isSupported;
  51408. },
  51409. enumerable: true,
  51410. configurable: true
  51411. });
  51412. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  51413. get: function () {
  51414. if (this._shareOutputWithPostProcess) {
  51415. return this._shareOutputWithPostProcess.aspectRatio;
  51416. }
  51417. if (this._forcedOutputTexture) {
  51418. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  51419. }
  51420. return this.width / this.height;
  51421. },
  51422. enumerable: true,
  51423. configurable: true
  51424. });
  51425. PostProcess.prototype.apply = function () {
  51426. // Check
  51427. if (!this._effect || !this._effect.isReady())
  51428. return null;
  51429. // States
  51430. this._engine.enableEffect(this._effect);
  51431. this._engine.setState(false);
  51432. this._engine.setDepthBuffer(false);
  51433. this._engine.setDepthWrite(false);
  51434. // Alpha
  51435. this._engine.setAlphaMode(this.alphaMode);
  51436. if (this.alphaConstants) {
  51437. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  51438. }
  51439. // Texture
  51440. var source;
  51441. if (this._shareOutputWithPostProcess) {
  51442. source = this._shareOutputWithPostProcess.outputTexture;
  51443. }
  51444. else if (this._forcedOutputTexture) {
  51445. source = this._forcedOutputTexture;
  51446. }
  51447. else {
  51448. source = this.outputTexture;
  51449. }
  51450. this._effect._bindTexture("textureSampler", source);
  51451. // Parameters
  51452. this._effect.setVector2("scale", this._scaleRatio);
  51453. this.onApplyObservable.notifyObservers(this._effect);
  51454. return this._effect;
  51455. };
  51456. PostProcess.prototype._disposeTextures = function () {
  51457. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  51458. return;
  51459. }
  51460. if (this._textures.length > 0) {
  51461. for (var i = 0; i < this._textures.length; i++) {
  51462. this._engine._releaseTexture(this._textures.data[i]);
  51463. }
  51464. }
  51465. this._textures.dispose();
  51466. };
  51467. PostProcess.prototype.dispose = function (camera) {
  51468. camera = camera || this._camera;
  51469. this._disposeTextures();
  51470. if (this._scene) {
  51471. var index_1 = this._scene.postProcesses.indexOf(this);
  51472. if (index_1 !== -1) {
  51473. this._scene.postProcesses.splice(index_1, 1);
  51474. }
  51475. }
  51476. else {
  51477. var index_2 = this._engine.postProcesses.indexOf(this);
  51478. if (index_2 !== -1) {
  51479. this._engine.postProcesses.splice(index_2, 1);
  51480. }
  51481. }
  51482. if (!camera) {
  51483. return;
  51484. }
  51485. camera.detachPostProcess(this);
  51486. var index = camera._postProcesses.indexOf(this);
  51487. if (index === 0 && camera._postProcesses.length > 0) {
  51488. this._camera._postProcesses[0].markTextureDirty();
  51489. }
  51490. this.onActivateObservable.clear();
  51491. this.onAfterRenderObservable.clear();
  51492. this.onApplyObservable.clear();
  51493. this.onBeforeRenderObservable.clear();
  51494. this.onSizeChangedObservable.clear();
  51495. };
  51496. return PostProcess;
  51497. }());
  51498. BABYLON.PostProcess = PostProcess;
  51499. })(BABYLON || (BABYLON = {}));
  51500. //# sourceMappingURL=babylon.postProcess.js.map
  51501. var BABYLON;
  51502. (function (BABYLON) {
  51503. var PassPostProcess = /** @class */ (function (_super) {
  51504. __extends(PassPostProcess, _super);
  51505. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  51506. if (camera === void 0) { camera = null; }
  51507. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51508. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  51509. }
  51510. return PassPostProcess;
  51511. }(BABYLON.PostProcess));
  51512. BABYLON.PassPostProcess = PassPostProcess;
  51513. })(BABYLON || (BABYLON = {}));
  51514. //# sourceMappingURL=babylon.passPostProcess.js.map
  51515. var __assign = (this && this.__assign) || Object.assign || function(t) {
  51516. for (var s, i = 1, n = arguments.length; i < n; i++) {
  51517. s = arguments[i];
  51518. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  51519. t[p] = s[p];
  51520. }
  51521. return t;
  51522. };
  51523. var BABYLON;
  51524. (function (BABYLON) {
  51525. var ShadowGenerator = /** @class */ (function () {
  51526. /**
  51527. * Creates a ShadowGenerator object.
  51528. * A ShadowGenerator is the required tool to use the shadows.
  51529. * Each light casting shadows needs to use its own ShadowGenerator.
  51530. * Required parameters :
  51531. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  51532. * - `light`: the light object generating the shadows.
  51533. * - `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.
  51534. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  51535. */
  51536. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  51537. // Members
  51538. this._bias = 0.00005;
  51539. this._blurBoxOffset = 1;
  51540. this._blurScale = 2;
  51541. this._blurKernel = 1;
  51542. this._useKernelBlur = false;
  51543. this._filter = ShadowGenerator.FILTER_NONE;
  51544. this._darkness = 0;
  51545. this._transparencyShadow = false;
  51546. /**
  51547. * Controls the extent to which the shadows fade out at the edge of the frustum
  51548. * Used only by directionals and spots
  51549. */
  51550. this.frustumEdgeFalloff = 0;
  51551. this.forceBackFacesOnly = false;
  51552. this._lightDirection = BABYLON.Vector3.Zero();
  51553. this._viewMatrix = BABYLON.Matrix.Zero();
  51554. this._projectionMatrix = BABYLON.Matrix.Zero();
  51555. this._transformMatrix = BABYLON.Matrix.Zero();
  51556. this._currentFaceIndex = 0;
  51557. this._currentFaceIndexCache = 0;
  51558. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  51559. this._mapSize = mapSize;
  51560. this._light = light;
  51561. this._scene = light.getScene();
  51562. light._shadowGenerator = this;
  51563. // Texture type fallback from float to int if not supported.
  51564. var caps = this._scene.getEngine().getCaps();
  51565. if (!useFullFloatFirst) {
  51566. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  51567. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  51568. }
  51569. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  51570. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  51571. }
  51572. else {
  51573. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  51574. }
  51575. }
  51576. else {
  51577. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  51578. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  51579. }
  51580. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  51581. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  51582. }
  51583. else {
  51584. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  51585. }
  51586. }
  51587. this._initializeGenerator();
  51588. }
  51589. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  51590. // Static
  51591. get: function () {
  51592. return ShadowGenerator._FILTER_NONE;
  51593. },
  51594. enumerable: true,
  51595. configurable: true
  51596. });
  51597. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  51598. get: function () {
  51599. return ShadowGenerator._FILTER_POISSONSAMPLING;
  51600. },
  51601. enumerable: true,
  51602. configurable: true
  51603. });
  51604. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  51605. get: function () {
  51606. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  51607. },
  51608. enumerable: true,
  51609. configurable: true
  51610. });
  51611. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  51612. get: function () {
  51613. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  51614. },
  51615. enumerable: true,
  51616. configurable: true
  51617. });
  51618. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  51619. get: function () {
  51620. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  51621. },
  51622. enumerable: true,
  51623. configurable: true
  51624. });
  51625. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  51626. get: function () {
  51627. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  51628. },
  51629. enumerable: true,
  51630. configurable: true
  51631. });
  51632. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  51633. get: function () {
  51634. return this._bias;
  51635. },
  51636. set: function (bias) {
  51637. this._bias = bias;
  51638. },
  51639. enumerable: true,
  51640. configurable: true
  51641. });
  51642. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  51643. get: function () {
  51644. return this._blurBoxOffset;
  51645. },
  51646. set: function (value) {
  51647. if (this._blurBoxOffset === value) {
  51648. return;
  51649. }
  51650. this._blurBoxOffset = value;
  51651. this._disposeBlurPostProcesses();
  51652. },
  51653. enumerable: true,
  51654. configurable: true
  51655. });
  51656. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  51657. get: function () {
  51658. return this._blurScale;
  51659. },
  51660. set: function (value) {
  51661. if (this._blurScale === value) {
  51662. return;
  51663. }
  51664. this._blurScale = value;
  51665. this._disposeBlurPostProcesses();
  51666. },
  51667. enumerable: true,
  51668. configurable: true
  51669. });
  51670. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  51671. get: function () {
  51672. return this._blurKernel;
  51673. },
  51674. set: function (value) {
  51675. if (this._blurKernel === value) {
  51676. return;
  51677. }
  51678. this._blurKernel = value;
  51679. this._disposeBlurPostProcesses();
  51680. },
  51681. enumerable: true,
  51682. configurable: true
  51683. });
  51684. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  51685. get: function () {
  51686. return this._useKernelBlur;
  51687. },
  51688. set: function (value) {
  51689. if (this._useKernelBlur === value) {
  51690. return;
  51691. }
  51692. this._useKernelBlur = value;
  51693. this._disposeBlurPostProcesses();
  51694. },
  51695. enumerable: true,
  51696. configurable: true
  51697. });
  51698. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  51699. get: function () {
  51700. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  51701. },
  51702. set: function (value) {
  51703. this._depthScale = value;
  51704. },
  51705. enumerable: true,
  51706. configurable: true
  51707. });
  51708. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  51709. get: function () {
  51710. return this._filter;
  51711. },
  51712. set: function (value) {
  51713. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  51714. if (this._light.needCube()) {
  51715. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  51716. this.useExponentialShadowMap = true;
  51717. return;
  51718. }
  51719. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  51720. this.useCloseExponentialShadowMap = true;
  51721. return;
  51722. }
  51723. }
  51724. if (this._filter === value) {
  51725. return;
  51726. }
  51727. this._filter = value;
  51728. this._disposeBlurPostProcesses();
  51729. this._applyFilterValues();
  51730. this._light._markMeshesAsLightDirty();
  51731. },
  51732. enumerable: true,
  51733. configurable: true
  51734. });
  51735. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  51736. get: function () {
  51737. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  51738. },
  51739. set: function (value) {
  51740. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  51741. return;
  51742. }
  51743. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  51744. },
  51745. enumerable: true,
  51746. configurable: true
  51747. });
  51748. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  51749. get: function () {
  51750. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  51751. return this.useExponentialShadowMap;
  51752. },
  51753. set: function (value) {
  51754. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  51755. this.useExponentialShadowMap = value;
  51756. },
  51757. enumerable: true,
  51758. configurable: true
  51759. });
  51760. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  51761. get: function () {
  51762. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  51763. return this.useBlurExponentialShadowMap;
  51764. },
  51765. set: function (value) {
  51766. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  51767. this.useBlurExponentialShadowMap = value;
  51768. },
  51769. enumerable: true,
  51770. configurable: true
  51771. });
  51772. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  51773. get: function () {
  51774. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  51775. },
  51776. set: function (value) {
  51777. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  51778. return;
  51779. }
  51780. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51781. },
  51782. enumerable: true,
  51783. configurable: true
  51784. });
  51785. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  51786. get: function () {
  51787. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  51788. },
  51789. set: function (value) {
  51790. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  51791. return;
  51792. }
  51793. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51794. },
  51795. enumerable: true,
  51796. configurable: true
  51797. });
  51798. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  51799. get: function () {
  51800. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  51801. },
  51802. set: function (value) {
  51803. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  51804. return;
  51805. }
  51806. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51807. },
  51808. enumerable: true,
  51809. configurable: true
  51810. });
  51811. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  51812. get: function () {
  51813. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  51814. },
  51815. set: function (value) {
  51816. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  51817. return;
  51818. }
  51819. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51820. },
  51821. enumerable: true,
  51822. configurable: true
  51823. });
  51824. /**
  51825. * Returns the darkness value (float).
  51826. */
  51827. ShadowGenerator.prototype.getDarkness = function () {
  51828. return this._darkness;
  51829. };
  51830. /**
  51831. * Sets the ShadowGenerator darkness value (float <= 1.0).
  51832. * Returns the ShadowGenerator.
  51833. */
  51834. ShadowGenerator.prototype.setDarkness = function (darkness) {
  51835. if (darkness >= 1.0)
  51836. this._darkness = 1.0;
  51837. else if (darkness <= 0.0)
  51838. this._darkness = 0.0;
  51839. else
  51840. this._darkness = darkness;
  51841. return this;
  51842. };
  51843. /**
  51844. * Sets the ability to have transparent shadow (boolean).
  51845. * Returns the ShadowGenerator.
  51846. */
  51847. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  51848. this._transparencyShadow = hasShadow;
  51849. return this;
  51850. };
  51851. /**
  51852. * Returns a RenderTargetTexture object : the shadow map texture.
  51853. */
  51854. ShadowGenerator.prototype.getShadowMap = function () {
  51855. return this._shadowMap;
  51856. };
  51857. /**
  51858. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  51859. */
  51860. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  51861. if (this._shadowMap2) {
  51862. return this._shadowMap2;
  51863. }
  51864. return this._shadowMap;
  51865. };
  51866. /**
  51867. * Helper function to add a mesh and its descendants to the list of shadow casters
  51868. * @param mesh Mesh to add
  51869. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  51870. */
  51871. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  51872. if (includeDescendants === void 0) { includeDescendants = true; }
  51873. if (!this._shadowMap) {
  51874. return this;
  51875. }
  51876. if (!this._shadowMap.renderList) {
  51877. this._shadowMap.renderList = [];
  51878. }
  51879. this._shadowMap.renderList.push(mesh);
  51880. if (includeDescendants) {
  51881. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  51882. }
  51883. return this;
  51884. var _a;
  51885. };
  51886. /**
  51887. * Helper function to remove a mesh and its descendants from the list of shadow casters
  51888. * @param mesh Mesh to remove
  51889. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  51890. */
  51891. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  51892. if (includeDescendants === void 0) { includeDescendants = true; }
  51893. if (!this._shadowMap || !this._shadowMap.renderList) {
  51894. return this;
  51895. }
  51896. var index = this._shadowMap.renderList.indexOf(mesh);
  51897. if (index !== -1) {
  51898. this._shadowMap.renderList.splice(index, 1);
  51899. }
  51900. if (includeDescendants) {
  51901. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  51902. var child = _a[_i];
  51903. this.removeShadowCaster(child);
  51904. }
  51905. }
  51906. return this;
  51907. };
  51908. /**
  51909. * Returns the associated light object.
  51910. */
  51911. ShadowGenerator.prototype.getLight = function () {
  51912. return this._light;
  51913. };
  51914. ShadowGenerator.prototype._initializeGenerator = function () {
  51915. this._light._markMeshesAsLightDirty();
  51916. this._initializeShadowMap();
  51917. };
  51918. ShadowGenerator.prototype._initializeShadowMap = function () {
  51919. var _this = this;
  51920. // Render target
  51921. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  51922. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51923. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51924. this._shadowMap.anisotropicFilteringLevel = 1;
  51925. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51926. this._shadowMap.renderParticles = false;
  51927. this._shadowMap.ignoreCameraViewport = true;
  51928. // Record Face Index before render.
  51929. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  51930. _this._currentFaceIndex = faceIndex;
  51931. });
  51932. // Custom render function.
  51933. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  51934. // Blur if required afer render.
  51935. this._shadowMap.onAfterUnbindObservable.add(function () {
  51936. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  51937. return;
  51938. }
  51939. if (!_this._blurPostProcesses || !_this._blurPostProcesses.length) {
  51940. _this._initializeBlurRTTAndPostProcesses();
  51941. }
  51942. var shadowMap = _this.getShadowMapForRendering();
  51943. if (shadowMap) {
  51944. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  51945. }
  51946. });
  51947. // Clear according to the chosen filter.
  51948. this._shadowMap.onClearObservable.add(function (engine) {
  51949. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  51950. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  51951. }
  51952. else {
  51953. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  51954. }
  51955. });
  51956. };
  51957. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  51958. var _this = this;
  51959. var engine = this._scene.getEngine();
  51960. var targetSize = this._mapSize / this.blurScale;
  51961. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  51962. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  51963. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51964. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51965. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51966. }
  51967. if (this.useKernelBlur) {
  51968. 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);
  51969. this._kernelBlurXPostprocess.width = targetSize;
  51970. this._kernelBlurXPostprocess.height = targetSize;
  51971. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  51972. effect.setTexture("textureSampler", _this._shadowMap);
  51973. });
  51974. 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);
  51975. this._kernelBlurXPostprocess.autoClear = false;
  51976. this._kernelBlurYPostprocess.autoClear = false;
  51977. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  51978. this._kernelBlurXPostprocess.packedFloat = true;
  51979. this._kernelBlurYPostprocess.packedFloat = true;
  51980. }
  51981. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  51982. }
  51983. else {
  51984. 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);
  51985. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  51986. effect.setFloat2("screenSize", targetSize, targetSize);
  51987. effect.setTexture("textureSampler", _this._shadowMap);
  51988. });
  51989. this._boxBlurPostprocess.autoClear = false;
  51990. this._blurPostProcesses = [this._boxBlurPostprocess];
  51991. }
  51992. };
  51993. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  51994. var index;
  51995. var engine = this._scene.getEngine();
  51996. if (depthOnlySubMeshes.length) {
  51997. engine.setColorWrite(false);
  51998. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  51999. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  52000. }
  52001. engine.setColorWrite(true);
  52002. }
  52003. for (index = 0; index < opaqueSubMeshes.length; index++) {
  52004. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  52005. }
  52006. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  52007. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  52008. }
  52009. if (this._transparencyShadow) {
  52010. for (index = 0; index < transparentSubMeshes.length; index++) {
  52011. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  52012. }
  52013. }
  52014. };
  52015. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  52016. var _this = this;
  52017. var mesh = subMesh.getRenderingMesh();
  52018. var scene = this._scene;
  52019. var engine = scene.getEngine();
  52020. var material = subMesh.getMaterial();
  52021. if (!material) {
  52022. return;
  52023. }
  52024. // Culling
  52025. engine.setState(material.backFaceCulling);
  52026. // Managing instances
  52027. var batch = mesh._getInstancesRenderList(subMesh._id);
  52028. if (batch.mustReturn) {
  52029. return;
  52030. }
  52031. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  52032. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  52033. engine.enableEffect(this._effect);
  52034. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  52035. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  52036. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  52037. this._effect.setVector3("lightPosition", this.getLight().position);
  52038. if (scene.activeCamera) {
  52039. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  52040. }
  52041. // Alpha test
  52042. if (material && material.needAlphaTesting()) {
  52043. var alphaTexture = material.getAlphaTestTexture();
  52044. if (alphaTexture) {
  52045. this._effect.setTexture("diffuseSampler", alphaTexture);
  52046. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  52047. }
  52048. }
  52049. // Bones
  52050. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52051. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  52052. }
  52053. if (this.forceBackFacesOnly) {
  52054. engine.setState(true, 0, false, true);
  52055. }
  52056. // Draw
  52057. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  52058. if (this.forceBackFacesOnly) {
  52059. engine.setState(true, 0, false, false);
  52060. }
  52061. }
  52062. else {
  52063. // Need to reset refresh rate of the shadowMap
  52064. if (this._shadowMap) {
  52065. this._shadowMap.resetRefreshCounter();
  52066. }
  52067. }
  52068. };
  52069. ShadowGenerator.prototype._applyFilterValues = function () {
  52070. if (!this._shadowMap) {
  52071. return;
  52072. }
  52073. if (this.filter === ShadowGenerator.FILTER_NONE) {
  52074. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  52075. }
  52076. else {
  52077. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52078. }
  52079. };
  52080. /**
  52081. * Force shader compilation including textures ready check
  52082. */
  52083. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  52084. var _this = this;
  52085. var localOptions = __assign({ useInstances: false }, options);
  52086. var shadowMap = this.getShadowMap();
  52087. if (!shadowMap) {
  52088. if (onCompiled) {
  52089. onCompiled(this);
  52090. }
  52091. return;
  52092. }
  52093. var renderList = shadowMap.renderList;
  52094. if (!renderList) {
  52095. if (onCompiled) {
  52096. onCompiled(this);
  52097. }
  52098. return;
  52099. }
  52100. var subMeshes = new Array();
  52101. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  52102. var mesh = renderList_1[_i];
  52103. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  52104. }
  52105. if (subMeshes.length === 0) {
  52106. if (onCompiled) {
  52107. onCompiled(this);
  52108. }
  52109. return;
  52110. }
  52111. var currentIndex = 0;
  52112. var checkReady = function () {
  52113. if (!_this._scene || !_this._scene.getEngine()) {
  52114. return;
  52115. }
  52116. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  52117. currentIndex++;
  52118. if (currentIndex >= subMeshes.length) {
  52119. if (onCompiled) {
  52120. onCompiled(_this);
  52121. }
  52122. return;
  52123. }
  52124. }
  52125. setTimeout(checkReady, 16);
  52126. };
  52127. checkReady();
  52128. };
  52129. /**
  52130. * Boolean : true when the ShadowGenerator is finally computed.
  52131. */
  52132. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  52133. var defines = [];
  52134. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  52135. defines.push("#define FLOAT");
  52136. }
  52137. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  52138. defines.push("#define ESM");
  52139. }
  52140. var attribs = [BABYLON.VertexBuffer.PositionKind];
  52141. var mesh = subMesh.getMesh();
  52142. var material = subMesh.getMaterial();
  52143. // Alpha test
  52144. if (material && material.needAlphaTesting()) {
  52145. var alphaTexture = material.getAlphaTestTexture();
  52146. if (alphaTexture) {
  52147. defines.push("#define ALPHATEST");
  52148. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52149. attribs.push(BABYLON.VertexBuffer.UVKind);
  52150. defines.push("#define UV1");
  52151. }
  52152. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52153. if (alphaTexture.coordinatesIndex === 1) {
  52154. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52155. defines.push("#define UV2");
  52156. }
  52157. }
  52158. }
  52159. }
  52160. // Bones
  52161. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52162. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52163. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52164. if (mesh.numBoneInfluencers > 4) {
  52165. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52166. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52167. }
  52168. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52169. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52170. }
  52171. else {
  52172. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52173. }
  52174. // Instances
  52175. if (useInstances) {
  52176. defines.push("#define INSTANCES");
  52177. attribs.push("world0");
  52178. attribs.push("world1");
  52179. attribs.push("world2");
  52180. attribs.push("world3");
  52181. }
  52182. // Get correct effect
  52183. var join = defines.join("\n");
  52184. if (this._cachedDefines !== join) {
  52185. this._cachedDefines = join;
  52186. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  52187. }
  52188. return this._effect.isReady();
  52189. };
  52190. /**
  52191. * This creates the defines related to the standard BJS materials.
  52192. */
  52193. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  52194. var scene = this._scene;
  52195. var light = this._light;
  52196. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  52197. return;
  52198. }
  52199. defines["SHADOW" + lightIndex] = true;
  52200. if (this.usePoissonSampling) {
  52201. defines["SHADOWPCF" + lightIndex] = true;
  52202. }
  52203. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  52204. defines["SHADOWESM" + lightIndex] = true;
  52205. }
  52206. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  52207. defines["SHADOWCLOSEESM" + lightIndex] = true;
  52208. }
  52209. if (light.needCube()) {
  52210. defines["SHADOWCUBE" + lightIndex] = true;
  52211. }
  52212. };
  52213. /**
  52214. * This binds shadow lights related to the standard BJS materials.
  52215. * It implies the unifroms available on the materials are the standard BJS ones.
  52216. */
  52217. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  52218. var light = this._light;
  52219. var scene = this._scene;
  52220. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  52221. return;
  52222. }
  52223. var camera = scene.activeCamera;
  52224. if (!camera) {
  52225. return;
  52226. }
  52227. var shadowMap = this.getShadowMap();
  52228. if (!shadowMap) {
  52229. return;
  52230. }
  52231. if (!light.needCube()) {
  52232. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  52233. }
  52234. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  52235. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  52236. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  52237. };
  52238. // Methods
  52239. /**
  52240. * Returns a Matrix object : the updated transformation matrix.
  52241. */
  52242. ShadowGenerator.prototype.getTransformMatrix = function () {
  52243. var scene = this._scene;
  52244. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  52245. return this._transformMatrix;
  52246. }
  52247. this._currentRenderID = scene.getRenderId();
  52248. this._currentFaceIndexCache = this._currentFaceIndex;
  52249. var lightPosition = this._light.position;
  52250. if (this._light.computeTransformedInformation()) {
  52251. lightPosition = this._light.transformedPosition;
  52252. }
  52253. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  52254. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  52255. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  52256. }
  52257. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  52258. this._cachedPosition = lightPosition.clone();
  52259. this._cachedDirection = this._lightDirection.clone();
  52260. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  52261. var shadowMap = this.getShadowMap();
  52262. if (shadowMap) {
  52263. var renderList = shadowMap.renderList;
  52264. if (renderList) {
  52265. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  52266. }
  52267. }
  52268. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  52269. }
  52270. return this._transformMatrix;
  52271. };
  52272. ShadowGenerator.prototype.recreateShadowMap = function () {
  52273. var shadowMap = this._shadowMap;
  52274. if (!shadowMap) {
  52275. return;
  52276. }
  52277. // Track render list.
  52278. var renderList = shadowMap.renderList;
  52279. // Clean up existing data.
  52280. this._disposeRTTandPostProcesses();
  52281. // Reinitializes.
  52282. this._initializeGenerator();
  52283. // Reaffect the filter to ensure a correct fallback if necessary.
  52284. this.filter = this.filter;
  52285. // Reaffect the filter.
  52286. this._applyFilterValues();
  52287. // Reaffect Render List.
  52288. this._shadowMap.renderList = renderList;
  52289. };
  52290. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  52291. if (this._shadowMap2) {
  52292. this._shadowMap2.dispose();
  52293. this._shadowMap2 = null;
  52294. }
  52295. if (this._downSamplePostprocess) {
  52296. this._downSamplePostprocess.dispose();
  52297. this._downSamplePostprocess = null;
  52298. }
  52299. if (this._boxBlurPostprocess) {
  52300. this._boxBlurPostprocess.dispose();
  52301. this._boxBlurPostprocess = null;
  52302. }
  52303. if (this._kernelBlurXPostprocess) {
  52304. this._kernelBlurXPostprocess.dispose();
  52305. this._kernelBlurXPostprocess = null;
  52306. }
  52307. if (this._kernelBlurYPostprocess) {
  52308. this._kernelBlurYPostprocess.dispose();
  52309. this._kernelBlurYPostprocess = null;
  52310. }
  52311. this._blurPostProcesses = [];
  52312. };
  52313. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  52314. if (this._shadowMap) {
  52315. this._shadowMap.dispose();
  52316. this._shadowMap = null;
  52317. }
  52318. this._disposeBlurPostProcesses();
  52319. };
  52320. /**
  52321. * Disposes the ShadowGenerator.
  52322. * Returns nothing.
  52323. */
  52324. ShadowGenerator.prototype.dispose = function () {
  52325. this._disposeRTTandPostProcesses();
  52326. if (this._light) {
  52327. this._light._shadowGenerator = null;
  52328. this._light._markMeshesAsLightDirty();
  52329. }
  52330. };
  52331. /**
  52332. * Serializes the ShadowGenerator and returns a serializationObject.
  52333. */
  52334. ShadowGenerator.prototype.serialize = function () {
  52335. var serializationObject = {};
  52336. var shadowMap = this.getShadowMap();
  52337. if (!shadowMap) {
  52338. return serializationObject;
  52339. }
  52340. serializationObject.lightId = this._light.id;
  52341. serializationObject.mapSize = shadowMap.getRenderSize();
  52342. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  52343. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  52344. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  52345. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  52346. serializationObject.usePoissonSampling = this.usePoissonSampling;
  52347. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  52348. serializationObject.depthScale = this.depthScale;
  52349. serializationObject.darkness = this.getDarkness();
  52350. serializationObject.blurBoxOffset = this.blurBoxOffset;
  52351. serializationObject.blurKernel = this.blurKernel;
  52352. serializationObject.blurScale = this.blurScale;
  52353. serializationObject.useKernelBlur = this.useKernelBlur;
  52354. serializationObject.transparencyShadow = this._transparencyShadow;
  52355. serializationObject.renderList = [];
  52356. if (shadowMap.renderList) {
  52357. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  52358. var mesh = shadowMap.renderList[meshIndex];
  52359. serializationObject.renderList.push(mesh.id);
  52360. }
  52361. }
  52362. return serializationObject;
  52363. };
  52364. /**
  52365. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  52366. */
  52367. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  52368. //casting to point light, as light is missing the position attr and typescript complains.
  52369. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  52370. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  52371. var shadowMap = shadowGenerator.getShadowMap();
  52372. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  52373. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  52374. meshes.forEach(function (mesh) {
  52375. if (!shadowMap) {
  52376. return;
  52377. }
  52378. if (!shadowMap.renderList) {
  52379. shadowMap.renderList = [];
  52380. }
  52381. shadowMap.renderList.push(mesh);
  52382. });
  52383. }
  52384. if (parsedShadowGenerator.usePoissonSampling) {
  52385. shadowGenerator.usePoissonSampling = true;
  52386. }
  52387. else if (parsedShadowGenerator.useExponentialShadowMap) {
  52388. shadowGenerator.useExponentialShadowMap = true;
  52389. }
  52390. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  52391. shadowGenerator.useBlurExponentialShadowMap = true;
  52392. }
  52393. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  52394. shadowGenerator.useCloseExponentialShadowMap = true;
  52395. }
  52396. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  52397. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  52398. }
  52399. else if (parsedShadowGenerator.useVarianceShadowMap) {
  52400. shadowGenerator.useExponentialShadowMap = true;
  52401. }
  52402. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  52403. shadowGenerator.useBlurExponentialShadowMap = true;
  52404. }
  52405. if (parsedShadowGenerator.depthScale) {
  52406. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  52407. }
  52408. if (parsedShadowGenerator.blurScale) {
  52409. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  52410. }
  52411. if (parsedShadowGenerator.blurBoxOffset) {
  52412. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  52413. }
  52414. if (parsedShadowGenerator.useKernelBlur) {
  52415. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  52416. }
  52417. if (parsedShadowGenerator.blurKernel) {
  52418. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  52419. }
  52420. if (parsedShadowGenerator.bias !== undefined) {
  52421. shadowGenerator.bias = parsedShadowGenerator.bias;
  52422. }
  52423. if (parsedShadowGenerator.darkness) {
  52424. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  52425. }
  52426. if (parsedShadowGenerator.transparencyShadow) {
  52427. shadowGenerator.setTransparencyShadow(true);
  52428. }
  52429. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  52430. return shadowGenerator;
  52431. };
  52432. ShadowGenerator._FILTER_NONE = 0;
  52433. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  52434. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  52435. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  52436. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  52437. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  52438. return ShadowGenerator;
  52439. }());
  52440. BABYLON.ShadowGenerator = ShadowGenerator;
  52441. })(BABYLON || (BABYLON = {}));
  52442. //# sourceMappingURL=babylon.shadowGenerator.js.map
  52443. var BABYLON;
  52444. (function (BABYLON) {
  52445. var DefaultLoadingScreen = /** @class */ (function () {
  52446. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  52447. if (_loadingText === void 0) { _loadingText = ""; }
  52448. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  52449. var _this = this;
  52450. this._renderingCanvas = _renderingCanvas;
  52451. this._loadingText = _loadingText;
  52452. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  52453. // Resize
  52454. this._resizeLoadingUI = function () {
  52455. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  52456. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  52457. if (!_this._loadingDiv) {
  52458. return;
  52459. }
  52460. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  52461. _this._loadingDiv.style.left = canvasRect.left + "px";
  52462. _this._loadingDiv.style.top = canvasRect.top + "px";
  52463. _this._loadingDiv.style.width = canvasRect.width + "px";
  52464. _this._loadingDiv.style.height = canvasRect.height + "px";
  52465. };
  52466. }
  52467. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  52468. if (this._loadingDiv) {
  52469. // Do not add a loading screen if there is already one
  52470. return;
  52471. }
  52472. this._loadingDiv = document.createElement("div");
  52473. this._loadingDiv.id = "babylonjsLoadingDiv";
  52474. this._loadingDiv.style.opacity = "0";
  52475. this._loadingDiv.style.transition = "opacity 1.5s ease";
  52476. this._loadingDiv.style.pointerEvents = "none";
  52477. // Loading text
  52478. this._loadingTextDiv = document.createElement("div");
  52479. this._loadingTextDiv.style.position = "absolute";
  52480. this._loadingTextDiv.style.left = "0";
  52481. this._loadingTextDiv.style.top = "50%";
  52482. this._loadingTextDiv.style.marginTop = "80px";
  52483. this._loadingTextDiv.style.width = "100%";
  52484. this._loadingTextDiv.style.height = "20px";
  52485. this._loadingTextDiv.style.fontFamily = "Arial";
  52486. this._loadingTextDiv.style.fontSize = "14px";
  52487. this._loadingTextDiv.style.color = "white";
  52488. this._loadingTextDiv.style.textAlign = "center";
  52489. this._loadingTextDiv.innerHTML = "Loading";
  52490. this._loadingDiv.appendChild(this._loadingTextDiv);
  52491. //set the predefined text
  52492. this._loadingTextDiv.innerHTML = this._loadingText;
  52493. // Generating keyframes
  52494. var style = document.createElement('style');
  52495. style.type = 'text/css';
  52496. 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 }";
  52497. style.innerHTML = keyFrames;
  52498. document.getElementsByTagName('head')[0].appendChild(style);
  52499. // Loading img
  52500. var imgBack = new Image();
  52501. 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";
  52502. imgBack.style.position = "absolute";
  52503. imgBack.style.left = "50%";
  52504. imgBack.style.top = "50%";
  52505. imgBack.style.marginLeft = "-60px";
  52506. imgBack.style.marginTop = "-60px";
  52507. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  52508. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  52509. imgBack.style.transformOrigin = "50% 50%";
  52510. imgBack.style.webkitTransformOrigin = "50% 50%";
  52511. this._loadingDiv.appendChild(imgBack);
  52512. this._resizeLoadingUI();
  52513. window.addEventListener("resize", this._resizeLoadingUI);
  52514. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  52515. document.body.appendChild(this._loadingDiv);
  52516. this._loadingDiv.style.opacity = "1";
  52517. };
  52518. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  52519. var _this = this;
  52520. if (!this._loadingDiv) {
  52521. return;
  52522. }
  52523. var onTransitionEnd = function () {
  52524. if (!_this._loadingDiv) {
  52525. return;
  52526. }
  52527. document.body.removeChild(_this._loadingDiv);
  52528. window.removeEventListener("resize", _this._resizeLoadingUI);
  52529. _this._loadingDiv = null;
  52530. };
  52531. this._loadingDiv.style.opacity = "0";
  52532. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  52533. };
  52534. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  52535. set: function (text) {
  52536. this._loadingText = text;
  52537. if (this._loadingTextDiv) {
  52538. this._loadingTextDiv.innerHTML = this._loadingText;
  52539. }
  52540. },
  52541. enumerable: true,
  52542. configurable: true
  52543. });
  52544. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  52545. get: function () {
  52546. return this._loadingDivBackgroundColor;
  52547. },
  52548. set: function (color) {
  52549. this._loadingDivBackgroundColor = color;
  52550. if (!this._loadingDiv) {
  52551. return;
  52552. }
  52553. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  52554. },
  52555. enumerable: true,
  52556. configurable: true
  52557. });
  52558. return DefaultLoadingScreen;
  52559. }());
  52560. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  52561. })(BABYLON || (BABYLON = {}));
  52562. //# sourceMappingURL=babylon.loadingScreen.js.map
  52563. var BABYLON;
  52564. (function (BABYLON) {
  52565. var SceneLoader = /** @class */ (function () {
  52566. function SceneLoader() {
  52567. }
  52568. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  52569. get: function () {
  52570. return 0;
  52571. },
  52572. enumerable: true,
  52573. configurable: true
  52574. });
  52575. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  52576. get: function () {
  52577. return 1;
  52578. },
  52579. enumerable: true,
  52580. configurable: true
  52581. });
  52582. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  52583. get: function () {
  52584. return 2;
  52585. },
  52586. enumerable: true,
  52587. configurable: true
  52588. });
  52589. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  52590. get: function () {
  52591. return 3;
  52592. },
  52593. enumerable: true,
  52594. configurable: true
  52595. });
  52596. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  52597. get: function () {
  52598. return SceneLoader._ForceFullSceneLoadingForIncremental;
  52599. },
  52600. set: function (value) {
  52601. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  52602. },
  52603. enumerable: true,
  52604. configurable: true
  52605. });
  52606. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  52607. get: function () {
  52608. return SceneLoader._ShowLoadingScreen;
  52609. },
  52610. set: function (value) {
  52611. SceneLoader._ShowLoadingScreen = value;
  52612. },
  52613. enumerable: true,
  52614. configurable: true
  52615. });
  52616. Object.defineProperty(SceneLoader, "loggingLevel", {
  52617. get: function () {
  52618. return SceneLoader._loggingLevel;
  52619. },
  52620. set: function (value) {
  52621. SceneLoader._loggingLevel = value;
  52622. },
  52623. enumerable: true,
  52624. configurable: true
  52625. });
  52626. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  52627. get: function () {
  52628. return SceneLoader._CleanBoneMatrixWeights;
  52629. },
  52630. set: function (value) {
  52631. SceneLoader._CleanBoneMatrixWeights = value;
  52632. },
  52633. enumerable: true,
  52634. configurable: true
  52635. });
  52636. SceneLoader._getDefaultPlugin = function () {
  52637. return SceneLoader._registeredPlugins[".babylon"];
  52638. };
  52639. SceneLoader._getPluginForExtension = function (extension) {
  52640. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  52641. if (registeredPlugin) {
  52642. return registeredPlugin;
  52643. }
  52644. return SceneLoader._getDefaultPlugin();
  52645. };
  52646. SceneLoader._getPluginForDirectLoad = function (data) {
  52647. for (var extension in SceneLoader._registeredPlugins) {
  52648. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  52649. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  52650. return SceneLoader._registeredPlugins[extension];
  52651. }
  52652. }
  52653. return SceneLoader._getDefaultPlugin();
  52654. };
  52655. SceneLoader._getPluginForFilename = function (sceneFilename) {
  52656. if (sceneFilename.name) {
  52657. sceneFilename = sceneFilename.name;
  52658. }
  52659. var queryStringPosition = sceneFilename.indexOf("?");
  52660. if (queryStringPosition !== -1) {
  52661. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  52662. }
  52663. var dotPosition = sceneFilename.lastIndexOf(".");
  52664. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  52665. return SceneLoader._getPluginForExtension(extension);
  52666. };
  52667. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  52668. SceneLoader._getDirectLoad = function (sceneFilename) {
  52669. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  52670. return sceneFilename.substr(5);
  52671. }
  52672. return null;
  52673. };
  52674. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  52675. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  52676. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  52677. var plugin;
  52678. if (registeredPlugin.plugin.createPlugin) {
  52679. plugin = registeredPlugin.plugin.createPlugin();
  52680. }
  52681. else {
  52682. plugin = registeredPlugin.plugin;
  52683. }
  52684. var useArrayBuffer = registeredPlugin.isBinary;
  52685. var database;
  52686. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  52687. var dataCallback = function (data, responseURL) {
  52688. if (scene.isDisposed) {
  52689. onError("Scene has been disposed");
  52690. return;
  52691. }
  52692. scene.database = database;
  52693. try {
  52694. onSuccess(plugin, data, responseURL);
  52695. }
  52696. catch (e) {
  52697. onError(null, e);
  52698. }
  52699. };
  52700. var manifestChecked = function (success) {
  52701. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  52702. if (request) {
  52703. onError(request.status + " " + request.statusText);
  52704. }
  52705. });
  52706. };
  52707. if (directLoad) {
  52708. dataCallback(directLoad);
  52709. return plugin;
  52710. }
  52711. if (rootUrl.indexOf("file:") === -1) {
  52712. if (scene.getEngine().enableOfflineSupport) {
  52713. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  52714. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  52715. }
  52716. else {
  52717. manifestChecked(true);
  52718. }
  52719. }
  52720. else {
  52721. var fileOrString = sceneFilename;
  52722. if (fileOrString.name) {
  52723. BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  52724. }
  52725. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  52726. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  52727. }
  52728. else {
  52729. onError("Unable to find file named " + sceneFilename);
  52730. }
  52731. }
  52732. return plugin;
  52733. };
  52734. // Public functions
  52735. SceneLoader.GetPluginForExtension = function (extension) {
  52736. return SceneLoader._getPluginForExtension(extension).plugin;
  52737. };
  52738. SceneLoader.RegisterPlugin = function (plugin) {
  52739. if (typeof plugin.extensions === "string") {
  52740. var extension = plugin.extensions;
  52741. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  52742. plugin: plugin,
  52743. isBinary: false
  52744. };
  52745. }
  52746. else {
  52747. var extensions = plugin.extensions;
  52748. Object.keys(extensions).forEach(function (extension) {
  52749. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  52750. plugin: plugin,
  52751. isBinary: extensions[extension].isBinary
  52752. };
  52753. });
  52754. }
  52755. };
  52756. /**
  52757. * Import meshes into a scene
  52758. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  52759. * @param rootUrl a string that defines the root url for scene and resources
  52760. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  52761. * @param scene the instance of BABYLON.Scene to append to
  52762. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  52763. * @param onProgress a callback with a progress event for each file being loaded
  52764. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  52765. */
  52766. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  52767. if (onSuccess === void 0) { onSuccess = null; }
  52768. if (onProgress === void 0) { onProgress = null; }
  52769. if (onError === void 0) { onError = null; }
  52770. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  52771. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  52772. return null;
  52773. }
  52774. var loadingToken = {};
  52775. scene._addPendingData(loadingToken);
  52776. var errorHandler = function (message, exception) {
  52777. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  52778. if (onError) {
  52779. onError(scene, errorMessage, exception);
  52780. }
  52781. else {
  52782. BABYLON.Tools.Error(errorMessage);
  52783. // should the exception be thrown?
  52784. }
  52785. scene._removePendingData(loadingToken);
  52786. };
  52787. var progressHandler = function (event) {
  52788. if (onProgress) {
  52789. onProgress(event);
  52790. }
  52791. };
  52792. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  52793. if (plugin.rewriteRootURL) {
  52794. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  52795. }
  52796. if (plugin.importMesh) {
  52797. var syncedPlugin = plugin;
  52798. var meshes = new Array();
  52799. var particleSystems = new Array();
  52800. var skeletons = new Array();
  52801. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  52802. return;
  52803. }
  52804. if (onSuccess) {
  52805. // wrap onSuccess with try-catch to know if something went wrong.
  52806. try {
  52807. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  52808. onSuccess(meshes, particleSystems, skeletons);
  52809. scene._removePendingData(loadingToken);
  52810. }
  52811. catch (e) {
  52812. var message = 'Error in onSuccess callback.';
  52813. errorHandler(message, e);
  52814. }
  52815. }
  52816. }
  52817. else {
  52818. var asyncedPlugin = plugin;
  52819. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  52820. if (onSuccess) {
  52821. try {
  52822. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  52823. onSuccess(meshes, particleSystems, skeletons);
  52824. scene._removePendingData(loadingToken);
  52825. }
  52826. catch (e) {
  52827. var message = 'Error in onSuccess callback.';
  52828. errorHandler(message, e);
  52829. }
  52830. }
  52831. }, progressHandler, errorHandler);
  52832. }
  52833. }, progressHandler, errorHandler, pluginExtension);
  52834. };
  52835. /**
  52836. * Load a scene
  52837. * @param rootUrl a string that defines the root url for scene and resources
  52838. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  52839. * @param engine is the instance of BABYLON.Engine to use to create the scene
  52840. * @param onSuccess a callback with the scene when import succeeds
  52841. * @param onProgress a callback with a progress event for each file being loaded
  52842. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  52843. */
  52844. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  52845. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  52846. };
  52847. /**
  52848. * Append a scene
  52849. * @param rootUrl a string that defines the root url for scene and resources
  52850. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  52851. * @param scene is the instance of BABYLON.Scene to append to
  52852. * @param onSuccess a callback with the scene when import succeeds
  52853. * @param onProgress a callback with a progress event for each file being loaded
  52854. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  52855. */
  52856. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  52857. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  52858. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  52859. return null;
  52860. }
  52861. if (SceneLoader.ShowLoadingScreen) {
  52862. scene.getEngine().displayLoadingUI();
  52863. }
  52864. var loadingToken = {};
  52865. scene._addPendingData(loadingToken);
  52866. var errorHandler = function (message, exception) {
  52867. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  52868. if (onError) {
  52869. onError(scene, errorMessage, exception);
  52870. }
  52871. else {
  52872. BABYLON.Tools.Error(errorMessage);
  52873. // should the exception be thrown?
  52874. }
  52875. scene._removePendingData(loadingToken);
  52876. scene.getEngine().hideLoadingUI();
  52877. };
  52878. var progressHandler = function (event) {
  52879. if (onProgress) {
  52880. onProgress(event);
  52881. }
  52882. };
  52883. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  52884. if (plugin.load) {
  52885. var syncedPlugin = plugin;
  52886. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  52887. return;
  52888. }
  52889. if (onSuccess) {
  52890. try {
  52891. onSuccess(scene);
  52892. }
  52893. catch (e) {
  52894. errorHandler("Error in onSuccess callback", e);
  52895. }
  52896. }
  52897. scene.loadingPluginName = plugin.name;
  52898. scene._removePendingData(loadingToken);
  52899. }
  52900. else {
  52901. var asyncedPlugin = plugin;
  52902. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  52903. if (onSuccess) {
  52904. onSuccess(scene);
  52905. }
  52906. scene.loadingPluginName = plugin.name;
  52907. scene._removePendingData(loadingToken);
  52908. }, progressHandler, errorHandler);
  52909. }
  52910. if (SceneLoader.ShowLoadingScreen) {
  52911. scene.executeWhenReady(function () {
  52912. scene.getEngine().hideLoadingUI();
  52913. });
  52914. }
  52915. }, progressHandler, errorHandler, pluginExtension);
  52916. };
  52917. // Flags
  52918. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  52919. SceneLoader._ShowLoadingScreen = true;
  52920. SceneLoader._CleanBoneMatrixWeights = false;
  52921. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  52922. // Members
  52923. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  52924. SceneLoader._registeredPlugins = {};
  52925. return SceneLoader;
  52926. }());
  52927. BABYLON.SceneLoader = SceneLoader;
  52928. ;
  52929. })(BABYLON || (BABYLON = {}));
  52930. //# sourceMappingURL=babylon.sceneLoader.js.map
  52931. var BABYLON;
  52932. (function (BABYLON) {
  52933. var Internals;
  52934. (function (Internals) {
  52935. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  52936. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  52937. var parsedMaterial = parsedData.materials[index];
  52938. if (parsedMaterial.id === id) {
  52939. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  52940. }
  52941. }
  52942. return null;
  52943. };
  52944. var isDescendantOf = function (mesh, names, hierarchyIds) {
  52945. for (var i in names) {
  52946. if (mesh.name === names[i]) {
  52947. hierarchyIds.push(mesh.id);
  52948. return true;
  52949. }
  52950. }
  52951. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  52952. hierarchyIds.push(mesh.id);
  52953. return true;
  52954. }
  52955. return false;
  52956. };
  52957. var logOperation = function (operation, producer) {
  52958. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  52959. };
  52960. BABYLON.SceneLoader.RegisterPlugin({
  52961. name: "babylon.js",
  52962. extensions: ".babylon",
  52963. canDirectLoad: function (data) {
  52964. if (data.indexOf("babylon") !== -1) {
  52965. return true;
  52966. }
  52967. return false;
  52968. },
  52969. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  52970. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  52971. // when SceneLoader.debugLogging = true (default), or exception encountered.
  52972. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  52973. // and avoid problems with multiple concurrent .babylon loads.
  52974. var log = "importMesh has failed JSON parse";
  52975. try {
  52976. var parsedData = JSON.parse(data);
  52977. log = "";
  52978. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  52979. if (!meshesNames) {
  52980. meshesNames = null;
  52981. }
  52982. else if (!Array.isArray(meshesNames)) {
  52983. meshesNames = [meshesNames];
  52984. }
  52985. var hierarchyIds = new Array();
  52986. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  52987. var loadedSkeletonsIds = [];
  52988. var loadedMaterialsIds = [];
  52989. var index;
  52990. var cache;
  52991. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  52992. var parsedMesh = parsedData.meshes[index];
  52993. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  52994. if (meshesNames !== null) {
  52995. // Remove found mesh name from list.
  52996. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  52997. }
  52998. //Geometry?
  52999. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  53000. //does the file contain geometries?
  53001. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  53002. //find the correct geometry and add it to the scene
  53003. var found = false;
  53004. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  53005. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  53006. return;
  53007. }
  53008. else {
  53009. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  53010. if (parsedGeometryData.id === parsedMesh.geometryId) {
  53011. switch (geometryType) {
  53012. case "boxes":
  53013. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  53014. break;
  53015. case "spheres":
  53016. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  53017. break;
  53018. case "cylinders":
  53019. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  53020. break;
  53021. case "toruses":
  53022. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  53023. break;
  53024. case "grounds":
  53025. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  53026. break;
  53027. case "planes":
  53028. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  53029. break;
  53030. case "torusKnots":
  53031. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  53032. break;
  53033. case "vertexData":
  53034. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  53035. break;
  53036. }
  53037. found = true;
  53038. }
  53039. });
  53040. }
  53041. });
  53042. if (found === false) {
  53043. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  53044. }
  53045. }
  53046. }
  53047. // Material ?
  53048. if (parsedMesh.materialId) {
  53049. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  53050. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  53051. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  53052. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  53053. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  53054. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  53055. var subMatId = parsedMultiMaterial.materials[matIndex];
  53056. loadedMaterialsIds.push(subMatId);
  53057. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  53058. log += "\n\tMaterial " + mat.toString(fullDetails);
  53059. }
  53060. loadedMaterialsIds.push(parsedMultiMaterial.id);
  53061. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  53062. materialFound = true;
  53063. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  53064. break;
  53065. }
  53066. }
  53067. }
  53068. if (materialFound === false) {
  53069. loadedMaterialsIds.push(parsedMesh.materialId);
  53070. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  53071. if (!mat) {
  53072. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  53073. }
  53074. else {
  53075. log += "\n\tMaterial " + mat.toString(fullDetails);
  53076. }
  53077. }
  53078. }
  53079. // Skeleton ?
  53080. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  53081. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  53082. if (skeletonAlreadyLoaded === false) {
  53083. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  53084. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  53085. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  53086. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  53087. skeletons.push(skeleton);
  53088. loadedSkeletonsIds.push(parsedSkeleton.id);
  53089. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  53090. }
  53091. }
  53092. }
  53093. }
  53094. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  53095. meshes.push(mesh);
  53096. log += "\n\tMesh " + mesh.toString(fullDetails);
  53097. }
  53098. }
  53099. // Connecting parents
  53100. var currentMesh;
  53101. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53102. currentMesh = scene.meshes[index];
  53103. if (currentMesh._waitingParentId) {
  53104. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  53105. currentMesh._waitingParentId = null;
  53106. }
  53107. }
  53108. // freeze and compute world matrix application
  53109. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53110. currentMesh = scene.meshes[index];
  53111. if (currentMesh._waitingFreezeWorldMatrix) {
  53112. currentMesh.freezeWorldMatrix();
  53113. currentMesh._waitingFreezeWorldMatrix = null;
  53114. }
  53115. else {
  53116. currentMesh.computeWorldMatrix(true);
  53117. }
  53118. }
  53119. }
  53120. // Particles
  53121. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  53122. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  53123. var parsedParticleSystem = parsedData.particleSystems[index];
  53124. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  53125. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  53126. }
  53127. }
  53128. }
  53129. return true;
  53130. }
  53131. catch (err) {
  53132. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  53133. if (onError) {
  53134. onError(msg, err);
  53135. }
  53136. else {
  53137. BABYLON.Tools.Log(msg);
  53138. throw err;
  53139. }
  53140. }
  53141. finally {
  53142. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  53143. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  53144. }
  53145. }
  53146. return false;
  53147. },
  53148. load: function (scene, data, rootUrl, onError) {
  53149. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  53150. // when SceneLoader.debugLogging = true (default), or exception encountered.
  53151. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  53152. // and avoid problems with multiple concurrent .babylon loads.
  53153. var log = "importScene has failed JSON parse";
  53154. try {
  53155. var parsedData = JSON.parse(data);
  53156. log = "";
  53157. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  53158. // Scene
  53159. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  53160. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  53161. }
  53162. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  53163. scene.autoClear = parsedData.autoClear;
  53164. }
  53165. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  53166. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  53167. }
  53168. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  53169. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  53170. }
  53171. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  53172. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  53173. }
  53174. // Fog
  53175. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  53176. scene.fogMode = parsedData.fogMode;
  53177. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  53178. scene.fogStart = parsedData.fogStart;
  53179. scene.fogEnd = parsedData.fogEnd;
  53180. scene.fogDensity = parsedData.fogDensity;
  53181. log += "\tFog mode for scene: ";
  53182. switch (scene.fogMode) {
  53183. // getters not compiling, so using hardcoded
  53184. case 1:
  53185. log += "exp\n";
  53186. break;
  53187. case 2:
  53188. log += "exp2\n";
  53189. break;
  53190. case 3:
  53191. log += "linear\n";
  53192. break;
  53193. }
  53194. }
  53195. //Physics
  53196. if (parsedData.physicsEnabled) {
  53197. var physicsPlugin;
  53198. if (parsedData.physicsEngine === "cannon") {
  53199. physicsPlugin = new BABYLON.CannonJSPlugin();
  53200. }
  53201. else if (parsedData.physicsEngine === "oimo") {
  53202. physicsPlugin = new BABYLON.OimoJSPlugin();
  53203. }
  53204. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  53205. //else - default engine, which is currently oimo
  53206. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  53207. scene.enablePhysics(physicsGravity, physicsPlugin);
  53208. }
  53209. // Metadata
  53210. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  53211. scene.metadata = parsedData.metadata;
  53212. }
  53213. //collisions, if defined. otherwise, default is true
  53214. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  53215. scene.collisionsEnabled = parsedData.collisionsEnabled;
  53216. }
  53217. scene.workerCollisions = !!parsedData.workerCollisions;
  53218. var index;
  53219. var cache;
  53220. // Lights
  53221. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  53222. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  53223. var parsedLight = parsedData.lights[index];
  53224. var light = BABYLON.Light.Parse(parsedLight, scene);
  53225. if (light) {
  53226. log += (index === 0 ? "\n\tLights:" : "");
  53227. log += "\n\t\t" + light.toString(fullDetails);
  53228. }
  53229. }
  53230. }
  53231. // Animations
  53232. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  53233. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  53234. var parsedAnimation = parsedData.animations[index];
  53235. var animation = BABYLON.Animation.Parse(parsedAnimation);
  53236. scene.animations.push(animation);
  53237. log += (index === 0 ? "\n\tAnimations:" : "");
  53238. log += "\n\t\t" + animation.toString(fullDetails);
  53239. }
  53240. }
  53241. if (parsedData.autoAnimate) {
  53242. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  53243. }
  53244. // Materials
  53245. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  53246. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  53247. var parsedMaterial = parsedData.materials[index];
  53248. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  53249. log += (index === 0 ? "\n\tMaterials:" : "");
  53250. log += "\n\t\t" + mat.toString(fullDetails);
  53251. }
  53252. }
  53253. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  53254. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  53255. var parsedMultiMaterial = parsedData.multiMaterials[index];
  53256. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  53257. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  53258. log += "\n\t\t" + mmat.toString(fullDetails);
  53259. }
  53260. }
  53261. // Morph targets
  53262. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  53263. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  53264. var managerData = _a[_i];
  53265. BABYLON.MorphTargetManager.Parse(managerData, scene);
  53266. }
  53267. }
  53268. // Skeletons
  53269. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  53270. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  53271. var parsedSkeleton = parsedData.skeletons[index];
  53272. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  53273. log += (index === 0 ? "\n\tSkeletons:" : "");
  53274. log += "\n\t\t" + skeleton.toString(fullDetails);
  53275. }
  53276. }
  53277. // Geometries
  53278. var geometries = parsedData.geometries;
  53279. if (geometries !== undefined && geometries !== null) {
  53280. // Boxes
  53281. var boxes = geometries.boxes;
  53282. if (boxes !== undefined && boxes !== null) {
  53283. for (index = 0, cache = boxes.length; index < cache; index++) {
  53284. var parsedBox = boxes[index];
  53285. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  53286. }
  53287. }
  53288. // Spheres
  53289. var spheres = geometries.spheres;
  53290. if (spheres !== undefined && spheres !== null) {
  53291. for (index = 0, cache = spheres.length; index < cache; index++) {
  53292. var parsedSphere = spheres[index];
  53293. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  53294. }
  53295. }
  53296. // Cylinders
  53297. var cylinders = geometries.cylinders;
  53298. if (cylinders !== undefined && cylinders !== null) {
  53299. for (index = 0, cache = cylinders.length; index < cache; index++) {
  53300. var parsedCylinder = cylinders[index];
  53301. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  53302. }
  53303. }
  53304. // Toruses
  53305. var toruses = geometries.toruses;
  53306. if (toruses !== undefined && toruses !== null) {
  53307. for (index = 0, cache = toruses.length; index < cache; index++) {
  53308. var parsedTorus = toruses[index];
  53309. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  53310. }
  53311. }
  53312. // Grounds
  53313. var grounds = geometries.grounds;
  53314. if (grounds !== undefined && grounds !== null) {
  53315. for (index = 0, cache = grounds.length; index < cache; index++) {
  53316. var parsedGround = grounds[index];
  53317. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  53318. }
  53319. }
  53320. // Planes
  53321. var planes = geometries.planes;
  53322. if (planes !== undefined && planes !== null) {
  53323. for (index = 0, cache = planes.length; index < cache; index++) {
  53324. var parsedPlane = planes[index];
  53325. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  53326. }
  53327. }
  53328. // TorusKnots
  53329. var torusKnots = geometries.torusKnots;
  53330. if (torusKnots !== undefined && torusKnots !== null) {
  53331. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  53332. var parsedTorusKnot = torusKnots[index];
  53333. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  53334. }
  53335. }
  53336. // VertexData
  53337. var vertexData = geometries.vertexData;
  53338. if (vertexData !== undefined && vertexData !== null) {
  53339. for (index = 0, cache = vertexData.length; index < cache; index++) {
  53340. var parsedVertexData = vertexData[index];
  53341. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  53342. }
  53343. }
  53344. }
  53345. // Transform nodes
  53346. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  53347. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  53348. var parsedTransformNode = parsedData.transformNodes[index];
  53349. BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  53350. }
  53351. }
  53352. // Meshes
  53353. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  53354. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  53355. var parsedMesh = parsedData.meshes[index];
  53356. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  53357. log += (index === 0 ? "\n\tMeshes:" : "");
  53358. log += "\n\t\t" + mesh.toString(fullDetails);
  53359. }
  53360. }
  53361. // Cameras
  53362. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  53363. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  53364. var parsedCamera = parsedData.cameras[index];
  53365. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  53366. log += (index === 0 ? "\n\tCameras:" : "");
  53367. log += "\n\t\t" + camera.toString(fullDetails);
  53368. }
  53369. }
  53370. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  53371. scene.setActiveCameraByID(parsedData.activeCameraID);
  53372. }
  53373. // Browsing all the graph to connect the dots
  53374. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  53375. var camera = scene.cameras[index];
  53376. if (camera._waitingParentId) {
  53377. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  53378. camera._waitingParentId = null;
  53379. }
  53380. }
  53381. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  53382. var light_1 = scene.lights[index];
  53383. if (light_1 && light_1._waitingParentId) {
  53384. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  53385. light_1._waitingParentId = null;
  53386. }
  53387. }
  53388. // Sounds
  53389. var loadedSounds = [];
  53390. var loadedSound;
  53391. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  53392. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  53393. var parsedSound = parsedData.sounds[index];
  53394. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53395. if (!parsedSound.url)
  53396. parsedSound.url = parsedSound.name;
  53397. if (!loadedSounds[parsedSound.url]) {
  53398. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  53399. loadedSounds[parsedSound.url] = loadedSound;
  53400. }
  53401. else {
  53402. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  53403. }
  53404. }
  53405. else {
  53406. new BABYLON.Sound(parsedSound.name, null, scene);
  53407. }
  53408. }
  53409. }
  53410. loadedSounds = [];
  53411. // Connect parents & children and parse actions
  53412. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  53413. var transformNode = scene.transformNodes[index];
  53414. if (transformNode._waitingParentId) {
  53415. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  53416. transformNode._waitingParentId = null;
  53417. }
  53418. }
  53419. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53420. var mesh = scene.meshes[index];
  53421. if (mesh._waitingParentId) {
  53422. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  53423. mesh._waitingParentId = null;
  53424. }
  53425. if (mesh._waitingActions) {
  53426. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  53427. mesh._waitingActions = null;
  53428. }
  53429. }
  53430. // freeze world matrix application
  53431. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53432. var currentMesh = scene.meshes[index];
  53433. if (currentMesh._waitingFreezeWorldMatrix) {
  53434. currentMesh.freezeWorldMatrix();
  53435. currentMesh._waitingFreezeWorldMatrix = null;
  53436. }
  53437. else {
  53438. currentMesh.computeWorldMatrix(true);
  53439. }
  53440. }
  53441. // Particles Systems
  53442. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  53443. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  53444. var parsedParticleSystem = parsedData.particleSystems[index];
  53445. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  53446. }
  53447. }
  53448. // Environment texture
  53449. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  53450. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  53451. if (parsedData.createDefaultSkybox === true) {
  53452. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  53453. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  53454. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  53455. }
  53456. }
  53457. // Lens flares
  53458. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  53459. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  53460. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  53461. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  53462. }
  53463. }
  53464. // Shadows
  53465. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  53466. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  53467. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  53468. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  53469. }
  53470. }
  53471. // Lights exclusions / inclusions
  53472. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  53473. var light_2 = scene.lights[index];
  53474. // Excluded check
  53475. if (light_2._excludedMeshesIds.length > 0) {
  53476. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  53477. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  53478. if (excludedMesh) {
  53479. light_2.excludedMeshes.push(excludedMesh);
  53480. }
  53481. }
  53482. light_2._excludedMeshesIds = [];
  53483. }
  53484. // Included check
  53485. if (light_2._includedOnlyMeshesIds.length > 0) {
  53486. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  53487. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  53488. if (includedOnlyMesh) {
  53489. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  53490. }
  53491. }
  53492. light_2._includedOnlyMeshesIds = [];
  53493. }
  53494. }
  53495. // Actions (scene)
  53496. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  53497. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  53498. }
  53499. // Finish
  53500. return true;
  53501. }
  53502. catch (err) {
  53503. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  53504. if (onError) {
  53505. onError(msg, err);
  53506. }
  53507. else {
  53508. BABYLON.Tools.Log(msg);
  53509. throw err;
  53510. }
  53511. }
  53512. finally {
  53513. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  53514. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  53515. }
  53516. }
  53517. return false;
  53518. }
  53519. });
  53520. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53521. })(BABYLON || (BABYLON = {}));
  53522. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  53523. var BABYLON;
  53524. (function (BABYLON) {
  53525. var FilesInput = /** @class */ (function () {
  53526. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  53527. this.onProcessFileCallback = function () { return true; };
  53528. this._engine = engine;
  53529. this._currentScene = scene;
  53530. this._sceneLoadedCallback = sceneLoadedCallback;
  53531. this._progressCallback = progressCallback;
  53532. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  53533. this._textureLoadingCallback = textureLoadingCallback;
  53534. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  53535. this._onReloadCallback = onReloadCallback;
  53536. this._errorCallback = errorCallback;
  53537. }
  53538. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  53539. var _this = this;
  53540. if (elementToMonitor) {
  53541. this._elementToMonitor = elementToMonitor;
  53542. this._dragEnterHandler = function (e) { _this.drag(e); };
  53543. this._dragOverHandler = function (e) { _this.drag(e); };
  53544. this._dropHandler = function (e) { _this.drop(e); };
  53545. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  53546. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  53547. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  53548. }
  53549. };
  53550. FilesInput.prototype.dispose = function () {
  53551. if (!this._elementToMonitor) {
  53552. return;
  53553. }
  53554. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  53555. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  53556. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  53557. };
  53558. FilesInput.prototype.renderFunction = function () {
  53559. if (this._additionalRenderLoopLogicCallback) {
  53560. this._additionalRenderLoopLogicCallback();
  53561. }
  53562. if (this._currentScene) {
  53563. if (this._textureLoadingCallback) {
  53564. var remaining = this._currentScene.getWaitingItemsCount();
  53565. if (remaining > 0) {
  53566. this._textureLoadingCallback(remaining);
  53567. }
  53568. }
  53569. this._currentScene.render();
  53570. }
  53571. };
  53572. FilesInput.prototype.drag = function (e) {
  53573. e.stopPropagation();
  53574. e.preventDefault();
  53575. };
  53576. FilesInput.prototype.drop = function (eventDrop) {
  53577. eventDrop.stopPropagation();
  53578. eventDrop.preventDefault();
  53579. this.loadFiles(eventDrop);
  53580. };
  53581. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  53582. var _this = this;
  53583. var reader = folder.createReader();
  53584. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  53585. reader.readEntries(function (entries) {
  53586. remaining.count += entries.length;
  53587. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  53588. var entry = entries_1[_i];
  53589. if (entry.isFile) {
  53590. entry.file(function (file) {
  53591. file.correctName = relativePath + file.name;
  53592. files.push(file);
  53593. if (--remaining.count === 0) {
  53594. callback();
  53595. }
  53596. });
  53597. }
  53598. else if (entry.isDirectory) {
  53599. _this._traverseFolder(entry, files, remaining, callback);
  53600. }
  53601. }
  53602. if (--remaining.count) {
  53603. callback();
  53604. }
  53605. });
  53606. };
  53607. FilesInput.prototype._processFiles = function (files) {
  53608. var skippedFiles = 0;
  53609. for (var i = 0; i < files.length; i++) {
  53610. var name = files[i].correctName.toLowerCase();
  53611. var extension = name.split('.').pop();
  53612. if (!this.onProcessFileCallback(files[i], name, extension)) {
  53613. skippedFiles++;
  53614. continue;
  53615. }
  53616. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  53617. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  53618. this._sceneFileToLoad = files[i];
  53619. }
  53620. else {
  53621. FilesInput.FilesToLoad[name] = files[i];
  53622. }
  53623. }
  53624. if (this._onReloadCallback) {
  53625. this._onReloadCallback(this._sceneFileToLoad);
  53626. }
  53627. else if (skippedFiles < files.length) {
  53628. this.reload();
  53629. }
  53630. };
  53631. FilesInput.prototype.loadFiles = function (event) {
  53632. var _this = this;
  53633. if (this._startingProcessingFilesCallback)
  53634. this._startingProcessingFilesCallback();
  53635. // Handling data transfer via drag'n'drop
  53636. if (event && event.dataTransfer && event.dataTransfer.files) {
  53637. this._filesToLoad = event.dataTransfer.files;
  53638. }
  53639. // Handling files from input files
  53640. if (event && event.target && event.target.files) {
  53641. this._filesToLoad = event.target.files;
  53642. }
  53643. if (this._filesToLoad && this._filesToLoad.length > 0) {
  53644. var files_1 = new Array();
  53645. var folders = [];
  53646. var items = event.dataTransfer ? event.dataTransfer.items : null;
  53647. for (var i = 0; i < this._filesToLoad.length; i++) {
  53648. var fileToLoad = this._filesToLoad[i];
  53649. var name_1 = fileToLoad.name.toLowerCase();
  53650. var entry = void 0;
  53651. fileToLoad.correctName = name_1;
  53652. if (items) {
  53653. var item = items[i];
  53654. if (item.getAsEntry) {
  53655. entry = item.getAsEntry();
  53656. }
  53657. else if (item.webkitGetAsEntry) {
  53658. entry = item.webkitGetAsEntry();
  53659. }
  53660. }
  53661. if (!entry) {
  53662. files_1.push(fileToLoad);
  53663. }
  53664. else {
  53665. if (entry.isDirectory) {
  53666. folders.push(entry);
  53667. }
  53668. else {
  53669. files_1.push(fileToLoad);
  53670. }
  53671. }
  53672. }
  53673. if (folders.length === 0) {
  53674. this._processFiles(files_1);
  53675. }
  53676. else {
  53677. var remaining = { count: folders.length };
  53678. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  53679. var folder = folders_1[_i];
  53680. this._traverseFolder(folder, files_1, remaining, function () {
  53681. _this._processFiles(files_1);
  53682. });
  53683. }
  53684. }
  53685. }
  53686. };
  53687. FilesInput.prototype.reload = function () {
  53688. var _this = this;
  53689. // If a ".babylon" file has been provided
  53690. if (this._sceneFileToLoad) {
  53691. if (this._currentScene) {
  53692. if (BABYLON.Tools.errorsCount > 0) {
  53693. BABYLON.Tools.ClearLogCache();
  53694. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  53695. }
  53696. this._engine.stopRenderLoop();
  53697. this._currentScene.dispose();
  53698. }
  53699. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  53700. _this._currentScene = newScene;
  53701. if (_this._sceneLoadedCallback) {
  53702. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  53703. }
  53704. // Wait for textures and shaders to be ready
  53705. _this._currentScene.executeWhenReady(function () {
  53706. _this._engine.runRenderLoop(function () {
  53707. _this.renderFunction();
  53708. });
  53709. });
  53710. }, function (progress) {
  53711. if (_this._progressCallback) {
  53712. _this._progressCallback(progress);
  53713. }
  53714. }, function (scene, message) {
  53715. _this._currentScene = scene;
  53716. if (_this._errorCallback) {
  53717. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  53718. }
  53719. });
  53720. }
  53721. else {
  53722. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  53723. }
  53724. };
  53725. FilesInput.FilesToLoad = {};
  53726. return FilesInput;
  53727. }());
  53728. BABYLON.FilesInput = FilesInput;
  53729. })(BABYLON || (BABYLON = {}));
  53730. //# sourceMappingURL=babylon.filesInput.js.map
  53731. var BABYLON;
  53732. (function (BABYLON) {
  53733. /**
  53734. * This class implement a typical dictionary using a string as key and the generic type T as value.
  53735. * The underlying implementation relies on an associative array to ensure the best performances.
  53736. * The value can be anything including 'null' but except 'undefined'
  53737. */
  53738. var StringDictionary = /** @class */ (function () {
  53739. function StringDictionary() {
  53740. this._count = 0;
  53741. this._data = {};
  53742. }
  53743. /**
  53744. * This will clear this dictionary and copy the content from the 'source' one.
  53745. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  53746. * @param source the dictionary to take the content from and copy to this dictionary
  53747. */
  53748. StringDictionary.prototype.copyFrom = function (source) {
  53749. var _this = this;
  53750. this.clear();
  53751. source.forEach(function (t, v) { return _this.add(t, v); });
  53752. };
  53753. /**
  53754. * Get a value based from its key
  53755. * @param key the given key to get the matching value from
  53756. * @return the value if found, otherwise undefined is returned
  53757. */
  53758. StringDictionary.prototype.get = function (key) {
  53759. var val = this._data[key];
  53760. if (val !== undefined) {
  53761. return val;
  53762. }
  53763. return undefined;
  53764. };
  53765. /**
  53766. * Get a value from its key or add it if it doesn't exist.
  53767. * This method will ensure you that a given key/data will be present in the dictionary.
  53768. * @param key the given key to get the matching value from
  53769. * @param factory the factory that will create the value if the key is not present in the dictionary.
  53770. * The factory will only be invoked if there's no data for the given key.
  53771. * @return the value corresponding to the key.
  53772. */
  53773. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  53774. var val = this.get(key);
  53775. if (val !== undefined) {
  53776. return val;
  53777. }
  53778. val = factory(key);
  53779. if (val) {
  53780. this.add(key, val);
  53781. }
  53782. return val;
  53783. };
  53784. /**
  53785. * Get a value from its key if present in the dictionary otherwise add it
  53786. * @param key the key to get the value from
  53787. * @param val if there's no such key/value pair in the dictionary add it with this value
  53788. * @return the value corresponding to the key
  53789. */
  53790. StringDictionary.prototype.getOrAdd = function (key, val) {
  53791. var curVal = this.get(key);
  53792. if (curVal !== undefined) {
  53793. return curVal;
  53794. }
  53795. this.add(key, val);
  53796. return val;
  53797. };
  53798. /**
  53799. * Check if there's a given key in the dictionary
  53800. * @param key the key to check for
  53801. * @return true if the key is present, false otherwise
  53802. */
  53803. StringDictionary.prototype.contains = function (key) {
  53804. return this._data[key] !== undefined;
  53805. };
  53806. /**
  53807. * Add a new key and its corresponding value
  53808. * @param key the key to add
  53809. * @param value the value corresponding to the key
  53810. * @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
  53811. */
  53812. StringDictionary.prototype.add = function (key, value) {
  53813. if (this._data[key] !== undefined) {
  53814. return false;
  53815. }
  53816. this._data[key] = value;
  53817. ++this._count;
  53818. return true;
  53819. };
  53820. StringDictionary.prototype.set = function (key, value) {
  53821. if (this._data[key] === undefined) {
  53822. return false;
  53823. }
  53824. this._data[key] = value;
  53825. return true;
  53826. };
  53827. /**
  53828. * Get the element of the given key and remove it from the dictionary
  53829. * @param key
  53830. */
  53831. StringDictionary.prototype.getAndRemove = function (key) {
  53832. var val = this.get(key);
  53833. if (val !== undefined) {
  53834. delete this._data[key];
  53835. --this._count;
  53836. return val;
  53837. }
  53838. return null;
  53839. };
  53840. /**
  53841. * Remove a key/value from the dictionary.
  53842. * @param key the key to remove
  53843. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  53844. */
  53845. StringDictionary.prototype.remove = function (key) {
  53846. if (this.contains(key)) {
  53847. delete this._data[key];
  53848. --this._count;
  53849. return true;
  53850. }
  53851. return false;
  53852. };
  53853. /**
  53854. * Clear the whole content of the dictionary
  53855. */
  53856. StringDictionary.prototype.clear = function () {
  53857. this._data = {};
  53858. this._count = 0;
  53859. };
  53860. Object.defineProperty(StringDictionary.prototype, "count", {
  53861. get: function () {
  53862. return this._count;
  53863. },
  53864. enumerable: true,
  53865. configurable: true
  53866. });
  53867. /**
  53868. * Execute a callback on each key/val of the dictionary.
  53869. * Note that you can remove any element in this dictionary in the callback implementation
  53870. * @param callback the callback to execute on a given key/value pair
  53871. */
  53872. StringDictionary.prototype.forEach = function (callback) {
  53873. for (var cur in this._data) {
  53874. var val = this._data[cur];
  53875. callback(cur, val);
  53876. }
  53877. };
  53878. /**
  53879. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  53880. * If the callback returns null or undefined the method will iterate to the next key/value pair
  53881. * Note that you can remove any element in this dictionary in the callback implementation
  53882. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  53883. */
  53884. StringDictionary.prototype.first = function (callback) {
  53885. for (var cur in this._data) {
  53886. var val = this._data[cur];
  53887. var res = callback(cur, val);
  53888. if (res) {
  53889. return res;
  53890. }
  53891. }
  53892. return null;
  53893. };
  53894. return StringDictionary;
  53895. }());
  53896. BABYLON.StringDictionary = StringDictionary;
  53897. })(BABYLON || (BABYLON = {}));
  53898. //# sourceMappingURL=babylon.stringDictionary.js.map
  53899. var BABYLON;
  53900. (function (BABYLON) {
  53901. var Tags = /** @class */ (function () {
  53902. function Tags() {
  53903. }
  53904. Tags.EnableFor = function (obj) {
  53905. obj._tags = obj._tags || {};
  53906. obj.hasTags = function () {
  53907. return Tags.HasTags(obj);
  53908. };
  53909. obj.addTags = function (tagsString) {
  53910. return Tags.AddTagsTo(obj, tagsString);
  53911. };
  53912. obj.removeTags = function (tagsString) {
  53913. return Tags.RemoveTagsFrom(obj, tagsString);
  53914. };
  53915. obj.matchesTagsQuery = function (tagsQuery) {
  53916. return Tags.MatchesQuery(obj, tagsQuery);
  53917. };
  53918. };
  53919. Tags.DisableFor = function (obj) {
  53920. delete obj._tags;
  53921. delete obj.hasTags;
  53922. delete obj.addTags;
  53923. delete obj.removeTags;
  53924. delete obj.matchesTagsQuery;
  53925. };
  53926. Tags.HasTags = function (obj) {
  53927. if (!obj._tags) {
  53928. return false;
  53929. }
  53930. return !BABYLON.Tools.IsEmpty(obj._tags);
  53931. };
  53932. Tags.GetTags = function (obj, asString) {
  53933. if (asString === void 0) { asString = true; }
  53934. if (!obj._tags) {
  53935. return null;
  53936. }
  53937. if (asString) {
  53938. var tagsArray = [];
  53939. for (var tag in obj._tags) {
  53940. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  53941. tagsArray.push(tag);
  53942. }
  53943. }
  53944. return tagsArray.join(" ");
  53945. }
  53946. else {
  53947. return obj._tags;
  53948. }
  53949. };
  53950. // the tags 'true' and 'false' are reserved and cannot be used as tags
  53951. // a tag cannot start with '||', '&&', and '!'
  53952. // it cannot contain whitespaces
  53953. Tags.AddTagsTo = function (obj, tagsString) {
  53954. if (!tagsString) {
  53955. return;
  53956. }
  53957. if (typeof tagsString !== "string") {
  53958. return;
  53959. }
  53960. var tags = tagsString.split(" ");
  53961. tags.forEach(function (tag, index, array) {
  53962. Tags._AddTagTo(obj, tag);
  53963. });
  53964. };
  53965. Tags._AddTagTo = function (obj, tag) {
  53966. tag = tag.trim();
  53967. if (tag === "" || tag === "true" || tag === "false") {
  53968. return;
  53969. }
  53970. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  53971. return;
  53972. }
  53973. Tags.EnableFor(obj);
  53974. obj._tags[tag] = true;
  53975. };
  53976. Tags.RemoveTagsFrom = function (obj, tagsString) {
  53977. if (!Tags.HasTags(obj)) {
  53978. return;
  53979. }
  53980. var tags = tagsString.split(" ");
  53981. for (var t in tags) {
  53982. Tags._RemoveTagFrom(obj, tags[t]);
  53983. }
  53984. };
  53985. Tags._RemoveTagFrom = function (obj, tag) {
  53986. delete obj._tags[tag];
  53987. };
  53988. Tags.MatchesQuery = function (obj, tagsQuery) {
  53989. if (tagsQuery === undefined) {
  53990. return true;
  53991. }
  53992. if (tagsQuery === "") {
  53993. return Tags.HasTags(obj);
  53994. }
  53995. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  53996. };
  53997. return Tags;
  53998. }());
  53999. BABYLON.Tags = Tags;
  54000. })(BABYLON || (BABYLON = {}));
  54001. //# sourceMappingURL=babylon.tags.js.map
  54002. var BABYLON;
  54003. (function (BABYLON) {
  54004. var Internals;
  54005. (function (Internals) {
  54006. var AndOrNotEvaluator = /** @class */ (function () {
  54007. function AndOrNotEvaluator() {
  54008. }
  54009. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  54010. if (!query.match(/\([^\(\)]*\)/g)) {
  54011. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  54012. }
  54013. else {
  54014. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  54015. // remove parenthesis
  54016. r = r.slice(1, r.length - 1);
  54017. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  54018. });
  54019. }
  54020. if (query === "true") {
  54021. return true;
  54022. }
  54023. if (query === "false") {
  54024. return false;
  54025. }
  54026. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  54027. };
  54028. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  54029. evaluateCallback = evaluateCallback || (function (r) {
  54030. return r === "true" ? true : false;
  54031. });
  54032. var result;
  54033. var or = parenthesisContent.split("||");
  54034. for (var i in or) {
  54035. if (or.hasOwnProperty(i)) {
  54036. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  54037. var and = ori.split("&&");
  54038. if (and.length > 1) {
  54039. for (var j = 0; j < and.length; ++j) {
  54040. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  54041. if (andj !== "true" && andj !== "false") {
  54042. if (andj[0] === "!") {
  54043. result = !evaluateCallback(andj.substring(1));
  54044. }
  54045. else {
  54046. result = evaluateCallback(andj);
  54047. }
  54048. }
  54049. else {
  54050. result = andj === "true" ? true : false;
  54051. }
  54052. if (!result) {
  54053. ori = "false";
  54054. break;
  54055. }
  54056. }
  54057. }
  54058. if (result || ori === "true") {
  54059. result = true;
  54060. break;
  54061. }
  54062. // result equals false (or undefined)
  54063. if (ori !== "true" && ori !== "false") {
  54064. if (ori[0] === "!") {
  54065. result = !evaluateCallback(ori.substring(1));
  54066. }
  54067. else {
  54068. result = evaluateCallback(ori);
  54069. }
  54070. }
  54071. else {
  54072. result = ori === "true" ? true : false;
  54073. }
  54074. }
  54075. }
  54076. // the whole parenthesis scope is replaced by 'true' or 'false'
  54077. return result ? "true" : "false";
  54078. };
  54079. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  54080. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  54081. // remove whitespaces
  54082. r = r.replace(/[\s]/g, function () { return ""; });
  54083. return r.length % 2 ? "!" : "";
  54084. });
  54085. booleanString = booleanString.trim();
  54086. if (booleanString === "!true") {
  54087. booleanString = "false";
  54088. }
  54089. else if (booleanString === "!false") {
  54090. booleanString = "true";
  54091. }
  54092. return booleanString;
  54093. };
  54094. return AndOrNotEvaluator;
  54095. }());
  54096. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  54097. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54098. })(BABYLON || (BABYLON = {}));
  54099. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  54100. var BABYLON;
  54101. (function (BABYLON) {
  54102. var Database = /** @class */ (function () {
  54103. function Database(urlToScene, callbackManifestChecked) {
  54104. // Handling various flavors of prefixed version of IndexedDB
  54105. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  54106. this.callbackManifestChecked = callbackManifestChecked;
  54107. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  54108. this.db = null;
  54109. this._enableSceneOffline = false;
  54110. this._enableTexturesOffline = false;
  54111. this.manifestVersionFound = 0;
  54112. this.mustUpdateRessources = false;
  54113. this.hasReachedQuota = false;
  54114. if (!Database.IDBStorageEnabled) {
  54115. this.callbackManifestChecked(true);
  54116. }
  54117. else {
  54118. this.checkManifestFile();
  54119. }
  54120. }
  54121. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  54122. get: function () {
  54123. return this._enableSceneOffline;
  54124. },
  54125. enumerable: true,
  54126. configurable: true
  54127. });
  54128. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  54129. get: function () {
  54130. return this._enableTexturesOffline;
  54131. },
  54132. enumerable: true,
  54133. configurable: true
  54134. });
  54135. Database.prototype.checkManifestFile = function () {
  54136. var _this = this;
  54137. var noManifestFile = function () {
  54138. _this._enableSceneOffline = false;
  54139. _this._enableTexturesOffline = false;
  54140. _this.callbackManifestChecked(false);
  54141. };
  54142. var timeStampUsed = false;
  54143. var manifestURL = this.currentSceneUrl + ".manifest";
  54144. var xhr = new XMLHttpRequest();
  54145. if (navigator.onLine) {
  54146. // Adding a timestamp to by-pass browsers' cache
  54147. timeStampUsed = true;
  54148. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  54149. }
  54150. xhr.open("GET", manifestURL, true);
  54151. xhr.addEventListener("load", function () {
  54152. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  54153. try {
  54154. var manifestFile = JSON.parse(xhr.response);
  54155. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  54156. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  54157. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  54158. _this.manifestVersionFound = manifestFile.version;
  54159. }
  54160. if (_this.callbackManifestChecked) {
  54161. _this.callbackManifestChecked(true);
  54162. }
  54163. }
  54164. catch (ex) {
  54165. noManifestFile();
  54166. }
  54167. }
  54168. else {
  54169. noManifestFile();
  54170. }
  54171. }, false);
  54172. xhr.addEventListener("error", function (event) {
  54173. if (timeStampUsed) {
  54174. timeStampUsed = false;
  54175. // Let's retry without the timeStamp
  54176. // It could fail when coupled with HTML5 Offline API
  54177. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  54178. xhr.open("GET", retryManifestURL, true);
  54179. xhr.send();
  54180. }
  54181. else {
  54182. noManifestFile();
  54183. }
  54184. }, false);
  54185. try {
  54186. xhr.send();
  54187. }
  54188. catch (ex) {
  54189. BABYLON.Tools.Error("Error on XHR send request.");
  54190. this.callbackManifestChecked(false);
  54191. }
  54192. };
  54193. Database.prototype.openAsync = function (successCallback, errorCallback) {
  54194. var _this = this;
  54195. var handleError = function () {
  54196. _this.isSupported = false;
  54197. if (errorCallback)
  54198. errorCallback();
  54199. };
  54200. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  54201. // Your browser doesn't support IndexedDB
  54202. this.isSupported = false;
  54203. if (errorCallback)
  54204. errorCallback();
  54205. }
  54206. else {
  54207. // If the DB hasn't been opened or created yet
  54208. if (!this.db) {
  54209. this.hasReachedQuota = false;
  54210. this.isSupported = true;
  54211. var request = this.idbFactory.open("babylonjs", 1);
  54212. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  54213. request.onerror = function (event) {
  54214. handleError();
  54215. };
  54216. // executes when a version change transaction cannot complete due to other active transactions
  54217. request.onblocked = function (event) {
  54218. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  54219. handleError();
  54220. };
  54221. // DB has been opened successfully
  54222. request.onsuccess = function (event) {
  54223. _this.db = request.result;
  54224. successCallback();
  54225. };
  54226. // Initialization of the DB. Creating Scenes & Textures stores
  54227. request.onupgradeneeded = function (event) {
  54228. _this.db = (event.target).result;
  54229. if (_this.db) {
  54230. try {
  54231. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  54232. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  54233. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  54234. }
  54235. catch (ex) {
  54236. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  54237. handleError();
  54238. }
  54239. }
  54240. };
  54241. }
  54242. else {
  54243. if (successCallback)
  54244. successCallback();
  54245. }
  54246. }
  54247. };
  54248. Database.prototype.loadImageFromDB = function (url, image) {
  54249. var _this = this;
  54250. var completeURL = Database.ReturnFullUrlLocation(url);
  54251. var saveAndLoadImage = function () {
  54252. if (!_this.hasReachedQuota && _this.db !== null) {
  54253. // the texture is not yet in the DB, let's try to save it
  54254. _this._saveImageIntoDBAsync(completeURL, image);
  54255. }
  54256. else {
  54257. image.src = url;
  54258. }
  54259. };
  54260. if (!this.mustUpdateRessources) {
  54261. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  54262. }
  54263. else {
  54264. saveAndLoadImage();
  54265. }
  54266. };
  54267. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  54268. if (this.isSupported && this.db !== null) {
  54269. var texture;
  54270. var transaction = this.db.transaction(["textures"]);
  54271. transaction.onabort = function (event) {
  54272. image.src = url;
  54273. };
  54274. transaction.oncomplete = function (event) {
  54275. var blobTextureURL;
  54276. if (texture) {
  54277. var URL = window.URL || window.webkitURL;
  54278. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  54279. image.onerror = function () {
  54280. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  54281. image.src = url;
  54282. };
  54283. image.src = blobTextureURL;
  54284. }
  54285. else {
  54286. notInDBCallback();
  54287. }
  54288. };
  54289. var getRequest = transaction.objectStore("textures").get(url);
  54290. getRequest.onsuccess = function (event) {
  54291. texture = (event.target).result;
  54292. };
  54293. getRequest.onerror = function (event) {
  54294. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  54295. image.src = url;
  54296. };
  54297. }
  54298. else {
  54299. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54300. image.src = url;
  54301. }
  54302. };
  54303. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  54304. var _this = this;
  54305. if (this.isSupported) {
  54306. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  54307. var generateBlobUrl = function () {
  54308. var blobTextureURL;
  54309. if (blob) {
  54310. var URL = window.URL || window.webkitURL;
  54311. try {
  54312. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  54313. }
  54314. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  54315. catch (ex) {
  54316. blobTextureURL = URL.createObjectURL(blob);
  54317. }
  54318. }
  54319. if (blobTextureURL) {
  54320. image.src = blobTextureURL;
  54321. }
  54322. };
  54323. if (Database.IsUASupportingBlobStorage) {
  54324. var xhr = new XMLHttpRequest(), blob;
  54325. xhr.open("GET", url, true);
  54326. xhr.responseType = "blob";
  54327. xhr.addEventListener("load", function () {
  54328. if (xhr.status === 200 && _this.db) {
  54329. // Blob as response (XHR2)
  54330. blob = xhr.response;
  54331. var transaction = _this.db.transaction(["textures"], "readwrite");
  54332. // the transaction could abort because of a QuotaExceededError error
  54333. transaction.onabort = function (event) {
  54334. try {
  54335. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  54336. var srcElement = (event.srcElement || event.target);
  54337. var error = srcElement.error;
  54338. if (error && error.name === "QuotaExceededError") {
  54339. _this.hasReachedQuota = true;
  54340. }
  54341. }
  54342. catch (ex) { }
  54343. generateBlobUrl();
  54344. };
  54345. transaction.oncomplete = function (event) {
  54346. generateBlobUrl();
  54347. };
  54348. var newTexture = { textureUrl: url, data: blob };
  54349. try {
  54350. // Put the blob into the dabase
  54351. var addRequest = transaction.objectStore("textures").put(newTexture);
  54352. addRequest.onsuccess = function (event) {
  54353. };
  54354. addRequest.onerror = function (event) {
  54355. generateBlobUrl();
  54356. };
  54357. }
  54358. catch (ex) {
  54359. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  54360. if (ex.code === 25) {
  54361. Database.IsUASupportingBlobStorage = false;
  54362. }
  54363. image.src = url;
  54364. }
  54365. }
  54366. else {
  54367. image.src = url;
  54368. }
  54369. }, false);
  54370. xhr.addEventListener("error", function (event) {
  54371. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  54372. image.src = url;
  54373. }, false);
  54374. xhr.send();
  54375. }
  54376. else {
  54377. image.src = url;
  54378. }
  54379. }
  54380. else {
  54381. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54382. image.src = url;
  54383. }
  54384. };
  54385. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  54386. var _this = this;
  54387. var updateVersion = function () {
  54388. // the version is not yet in the DB or we need to update it
  54389. _this._saveVersionIntoDBAsync(url, versionLoaded);
  54390. };
  54391. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  54392. };
  54393. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  54394. var _this = this;
  54395. if (this.isSupported && this.db) {
  54396. var version;
  54397. try {
  54398. var transaction = this.db.transaction(["versions"]);
  54399. transaction.oncomplete = function (event) {
  54400. if (version) {
  54401. // If the version in the JSON file is > than the version in DB
  54402. if (_this.manifestVersionFound > version.data) {
  54403. _this.mustUpdateRessources = true;
  54404. updateInDBCallback();
  54405. }
  54406. else {
  54407. callback(version.data);
  54408. }
  54409. }
  54410. else {
  54411. _this.mustUpdateRessources = true;
  54412. updateInDBCallback();
  54413. }
  54414. };
  54415. transaction.onabort = function (event) {
  54416. callback(-1);
  54417. };
  54418. var getRequest = transaction.objectStore("versions").get(url);
  54419. getRequest.onsuccess = function (event) {
  54420. version = (event.target).result;
  54421. };
  54422. getRequest.onerror = function (event) {
  54423. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  54424. callback(-1);
  54425. };
  54426. }
  54427. catch (ex) {
  54428. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  54429. callback(-1);
  54430. }
  54431. }
  54432. else {
  54433. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54434. callback(-1);
  54435. }
  54436. };
  54437. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  54438. var _this = this;
  54439. if (this.isSupported && !this.hasReachedQuota && this.db) {
  54440. try {
  54441. // Open a transaction to the database
  54442. var transaction = this.db.transaction(["versions"], "readwrite");
  54443. // the transaction could abort because of a QuotaExceededError error
  54444. transaction.onabort = function (event) {
  54445. try {
  54446. var error = event.srcElement['error'];
  54447. if (error && error.name === "QuotaExceededError") {
  54448. _this.hasReachedQuota = true;
  54449. }
  54450. }
  54451. catch (ex) { }
  54452. callback(-1);
  54453. };
  54454. transaction.oncomplete = function (event) {
  54455. callback(_this.manifestVersionFound);
  54456. };
  54457. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  54458. // Put the scene into the database
  54459. var addRequest = transaction.objectStore("versions").put(newVersion);
  54460. addRequest.onsuccess = function (event) {
  54461. };
  54462. addRequest.onerror = function (event) {
  54463. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  54464. };
  54465. }
  54466. catch (ex) {
  54467. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  54468. callback(-1);
  54469. }
  54470. }
  54471. else {
  54472. callback(-1);
  54473. }
  54474. };
  54475. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  54476. var _this = this;
  54477. var completeUrl = Database.ReturnFullUrlLocation(url);
  54478. var saveAndLoadFile = function () {
  54479. // the scene is not yet in the DB, let's try to save it
  54480. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  54481. };
  54482. this._checkVersionFromDB(completeUrl, function (version) {
  54483. if (version !== -1) {
  54484. if (!_this.mustUpdateRessources) {
  54485. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  54486. }
  54487. else {
  54488. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  54489. }
  54490. }
  54491. else {
  54492. if (errorCallback) {
  54493. errorCallback();
  54494. }
  54495. }
  54496. });
  54497. };
  54498. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  54499. if (this.isSupported && this.db) {
  54500. var targetStore;
  54501. if (url.indexOf(".babylon") !== -1) {
  54502. targetStore = "scenes";
  54503. }
  54504. else {
  54505. targetStore = "textures";
  54506. }
  54507. var file;
  54508. var transaction = this.db.transaction([targetStore]);
  54509. transaction.oncomplete = function (event) {
  54510. if (file) {
  54511. callback(file.data);
  54512. }
  54513. else {
  54514. notInDBCallback();
  54515. }
  54516. };
  54517. transaction.onabort = function (event) {
  54518. notInDBCallback();
  54519. };
  54520. var getRequest = transaction.objectStore(targetStore).get(url);
  54521. getRequest.onsuccess = function (event) {
  54522. file = (event.target).result;
  54523. };
  54524. getRequest.onerror = function (event) {
  54525. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  54526. notInDBCallback();
  54527. };
  54528. }
  54529. else {
  54530. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54531. callback();
  54532. }
  54533. };
  54534. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  54535. var _this = this;
  54536. if (this.isSupported) {
  54537. var targetStore;
  54538. if (url.indexOf(".babylon") !== -1) {
  54539. targetStore = "scenes";
  54540. }
  54541. else {
  54542. targetStore = "textures";
  54543. }
  54544. // Create XHR
  54545. var xhr = new XMLHttpRequest();
  54546. var fileData;
  54547. xhr.open("GET", url, true);
  54548. if (useArrayBuffer) {
  54549. xhr.responseType = "arraybuffer";
  54550. }
  54551. if (progressCallback) {
  54552. xhr.onprogress = progressCallback;
  54553. }
  54554. xhr.addEventListener("load", function () {
  54555. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  54556. // Blob as response (XHR2)
  54557. //fileData = xhr.responseText;
  54558. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  54559. if (!_this.hasReachedQuota && _this.db) {
  54560. // Open a transaction to the database
  54561. var transaction = _this.db.transaction([targetStore], "readwrite");
  54562. // the transaction could abort because of a QuotaExceededError error
  54563. transaction.onabort = function (event) {
  54564. try {
  54565. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  54566. var error = event.srcElement['error'];
  54567. if (error && error.name === "QuotaExceededError") {
  54568. _this.hasReachedQuota = true;
  54569. }
  54570. }
  54571. catch (ex) { }
  54572. callback(fileData);
  54573. };
  54574. transaction.oncomplete = function (event) {
  54575. callback(fileData);
  54576. };
  54577. var newFile;
  54578. if (targetStore === "scenes") {
  54579. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  54580. }
  54581. else {
  54582. newFile = { textureUrl: url, data: fileData };
  54583. }
  54584. try {
  54585. // Put the scene into the database
  54586. var addRequest = transaction.objectStore(targetStore).put(newFile);
  54587. addRequest.onsuccess = function (event) {
  54588. };
  54589. addRequest.onerror = function (event) {
  54590. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  54591. };
  54592. }
  54593. catch (ex) {
  54594. callback(fileData);
  54595. }
  54596. }
  54597. else {
  54598. callback(fileData);
  54599. }
  54600. }
  54601. else {
  54602. callback();
  54603. }
  54604. }, false);
  54605. xhr.addEventListener("error", function (event) {
  54606. BABYLON.Tools.Error("error on XHR request.");
  54607. callback();
  54608. }, false);
  54609. xhr.send();
  54610. }
  54611. else {
  54612. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54613. callback();
  54614. }
  54615. };
  54616. Database.IsUASupportingBlobStorage = true;
  54617. Database.IDBStorageEnabled = true;
  54618. Database.parseURL = function (url) {
  54619. var a = document.createElement('a');
  54620. a.href = url;
  54621. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  54622. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  54623. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  54624. return absLocation;
  54625. };
  54626. Database.ReturnFullUrlLocation = function (url) {
  54627. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  54628. return (Database.parseURL(window.location.href) + url);
  54629. }
  54630. else {
  54631. return url;
  54632. }
  54633. };
  54634. return Database;
  54635. }());
  54636. BABYLON.Database = Database;
  54637. })(BABYLON || (BABYLON = {}));
  54638. //# sourceMappingURL=babylon.database.js.map
  54639. var BABYLON;
  54640. (function (BABYLON) {
  54641. var FresnelParameters = /** @class */ (function () {
  54642. function FresnelParameters() {
  54643. this._isEnabled = true;
  54644. this.leftColor = BABYLON.Color3.White();
  54645. this.rightColor = BABYLON.Color3.Black();
  54646. this.bias = 0;
  54647. this.power = 1;
  54648. }
  54649. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  54650. get: function () {
  54651. return this._isEnabled;
  54652. },
  54653. set: function (value) {
  54654. if (this._isEnabled === value) {
  54655. return;
  54656. }
  54657. this._isEnabled = value;
  54658. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  54659. },
  54660. enumerable: true,
  54661. configurable: true
  54662. });
  54663. FresnelParameters.prototype.clone = function () {
  54664. var newFresnelParameters = new FresnelParameters();
  54665. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  54666. return newFresnelParameters;
  54667. };
  54668. FresnelParameters.prototype.serialize = function () {
  54669. var serializationObject = {};
  54670. serializationObject.isEnabled = this.isEnabled;
  54671. serializationObject.leftColor = this.leftColor;
  54672. serializationObject.rightColor = this.rightColor;
  54673. serializationObject.bias = this.bias;
  54674. serializationObject.power = this.power;
  54675. return serializationObject;
  54676. };
  54677. FresnelParameters.Parse = function (parsedFresnelParameters) {
  54678. var fresnelParameters = new FresnelParameters();
  54679. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  54680. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  54681. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  54682. fresnelParameters.bias = parsedFresnelParameters.bias;
  54683. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  54684. return fresnelParameters;
  54685. };
  54686. return FresnelParameters;
  54687. }());
  54688. BABYLON.FresnelParameters = FresnelParameters;
  54689. })(BABYLON || (BABYLON = {}));
  54690. //# sourceMappingURL=babylon.fresnelParameters.js.map
  54691. var BABYLON;
  54692. (function (BABYLON) {
  54693. var MultiMaterial = /** @class */ (function (_super) {
  54694. __extends(MultiMaterial, _super);
  54695. function MultiMaterial(name, scene) {
  54696. var _this = _super.call(this, name, scene, true) || this;
  54697. scene.multiMaterials.push(_this);
  54698. _this.subMaterials = new Array();
  54699. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  54700. return _this;
  54701. }
  54702. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  54703. get: function () {
  54704. return this._subMaterials;
  54705. },
  54706. set: function (value) {
  54707. this._subMaterials = value;
  54708. this._hookArray(value);
  54709. },
  54710. enumerable: true,
  54711. configurable: true
  54712. });
  54713. MultiMaterial.prototype._hookArray = function (array) {
  54714. var _this = this;
  54715. var oldPush = array.push;
  54716. array.push = function () {
  54717. var items = [];
  54718. for (var _i = 0; _i < arguments.length; _i++) {
  54719. items[_i] = arguments[_i];
  54720. }
  54721. var result = oldPush.apply(array, items);
  54722. _this._markAllSubMeshesAsTexturesDirty();
  54723. return result;
  54724. };
  54725. var oldSplice = array.splice;
  54726. array.splice = function (index, deleteCount) {
  54727. var deleted = oldSplice.apply(array, [index, deleteCount]);
  54728. _this._markAllSubMeshesAsTexturesDirty();
  54729. return deleted;
  54730. };
  54731. };
  54732. // Properties
  54733. MultiMaterial.prototype.getSubMaterial = function (index) {
  54734. if (index < 0 || index >= this.subMaterials.length) {
  54735. return this.getScene().defaultMaterial;
  54736. }
  54737. return this.subMaterials[index];
  54738. };
  54739. MultiMaterial.prototype.getActiveTextures = function () {
  54740. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  54741. if (subMaterial) {
  54742. return subMaterial.getActiveTextures();
  54743. }
  54744. else {
  54745. return [];
  54746. }
  54747. }));
  54748. var _a;
  54749. };
  54750. // Methods
  54751. MultiMaterial.prototype.getClassName = function () {
  54752. return "MultiMaterial";
  54753. };
  54754. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  54755. for (var index = 0; index < this.subMaterials.length; index++) {
  54756. var subMaterial = this.subMaterials[index];
  54757. if (subMaterial) {
  54758. if (subMaterial.storeEffectOnSubMeshes) {
  54759. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  54760. return false;
  54761. }
  54762. continue;
  54763. }
  54764. if (!subMaterial.isReady(mesh)) {
  54765. return false;
  54766. }
  54767. }
  54768. }
  54769. return true;
  54770. };
  54771. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  54772. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  54773. for (var index = 0; index < this.subMaterials.length; index++) {
  54774. var subMaterial = null;
  54775. var current = this.subMaterials[index];
  54776. if (cloneChildren && current) {
  54777. subMaterial = current.clone(name + "-" + current.name);
  54778. }
  54779. else {
  54780. subMaterial = this.subMaterials[index];
  54781. }
  54782. newMultiMaterial.subMaterials.push(subMaterial);
  54783. }
  54784. return newMultiMaterial;
  54785. };
  54786. MultiMaterial.prototype.serialize = function () {
  54787. var serializationObject = {};
  54788. serializationObject.name = this.name;
  54789. serializationObject.id = this.id;
  54790. serializationObject.tags = BABYLON.Tags.GetTags(this);
  54791. serializationObject.materials = [];
  54792. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  54793. var subMat = this.subMaterials[matIndex];
  54794. if (subMat) {
  54795. serializationObject.materials.push(subMat.id);
  54796. }
  54797. else {
  54798. serializationObject.materials.push(null);
  54799. }
  54800. }
  54801. return serializationObject;
  54802. };
  54803. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54804. var scene = this.getScene();
  54805. if (!scene) {
  54806. return;
  54807. }
  54808. var index = scene.multiMaterials.indexOf(this);
  54809. if (index >= 0) {
  54810. scene.multiMaterials.splice(index, 1);
  54811. }
  54812. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54813. };
  54814. return MultiMaterial;
  54815. }(BABYLON.Material));
  54816. BABYLON.MultiMaterial = MultiMaterial;
  54817. })(BABYLON || (BABYLON = {}));
  54818. //# sourceMappingURL=babylon.multiMaterial.js.map
  54819. var BABYLON;
  54820. (function (BABYLON) {
  54821. var FreeCameraTouchInput = /** @class */ (function () {
  54822. function FreeCameraTouchInput() {
  54823. this._offsetX = null;
  54824. this._offsetY = null;
  54825. this._pointerPressed = new Array();
  54826. this.touchAngularSensibility = 200000.0;
  54827. this.touchMoveSensibility = 250.0;
  54828. }
  54829. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  54830. var _this = this;
  54831. var previousPosition = null;
  54832. if (this._pointerInput === undefined) {
  54833. this._onLostFocus = function (evt) {
  54834. _this._offsetX = null;
  54835. _this._offsetY = null;
  54836. };
  54837. this._pointerInput = function (p, s) {
  54838. var evt = p.event;
  54839. if (evt.pointerType === "mouse") {
  54840. return;
  54841. }
  54842. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  54843. if (!noPreventDefault) {
  54844. evt.preventDefault();
  54845. }
  54846. _this._pointerPressed.push(evt.pointerId);
  54847. if (_this._pointerPressed.length !== 1) {
  54848. return;
  54849. }
  54850. previousPosition = {
  54851. x: evt.clientX,
  54852. y: evt.clientY
  54853. };
  54854. }
  54855. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  54856. if (!noPreventDefault) {
  54857. evt.preventDefault();
  54858. }
  54859. var index = _this._pointerPressed.indexOf(evt.pointerId);
  54860. if (index === -1) {
  54861. return;
  54862. }
  54863. _this._pointerPressed.splice(index, 1);
  54864. if (index != 0) {
  54865. return;
  54866. }
  54867. previousPosition = null;
  54868. _this._offsetX = null;
  54869. _this._offsetY = null;
  54870. }
  54871. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  54872. if (!noPreventDefault) {
  54873. evt.preventDefault();
  54874. }
  54875. if (!previousPosition) {
  54876. return;
  54877. }
  54878. var index = _this._pointerPressed.indexOf(evt.pointerId);
  54879. if (index != 0) {
  54880. return;
  54881. }
  54882. _this._offsetX = evt.clientX - previousPosition.x;
  54883. _this._offsetY = -(evt.clientY - previousPosition.y);
  54884. }
  54885. };
  54886. }
  54887. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  54888. if (this._onLostFocus) {
  54889. element.addEventListener("blur", this._onLostFocus);
  54890. }
  54891. };
  54892. FreeCameraTouchInput.prototype.detachControl = function (element) {
  54893. if (this._pointerInput && element) {
  54894. if (this._observer) {
  54895. this.camera.getScene().onPointerObservable.remove(this._observer);
  54896. this._observer = null;
  54897. }
  54898. if (this._onLostFocus) {
  54899. element.removeEventListener("blur", this._onLostFocus);
  54900. this._onLostFocus = null;
  54901. }
  54902. this._pointerPressed = [];
  54903. this._offsetX = null;
  54904. this._offsetY = null;
  54905. }
  54906. };
  54907. FreeCameraTouchInput.prototype.checkInputs = function () {
  54908. if (this._offsetX && this._offsetY) {
  54909. var camera = this.camera;
  54910. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  54911. if (this._pointerPressed.length > 1) {
  54912. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  54913. }
  54914. else {
  54915. var speed = camera._computeLocalCameraSpeed();
  54916. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  54917. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  54918. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  54919. }
  54920. }
  54921. };
  54922. FreeCameraTouchInput.prototype.getClassName = function () {
  54923. return "FreeCameraTouchInput";
  54924. };
  54925. FreeCameraTouchInput.prototype.getSimpleName = function () {
  54926. return "touch";
  54927. };
  54928. __decorate([
  54929. BABYLON.serialize()
  54930. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  54931. __decorate([
  54932. BABYLON.serialize()
  54933. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  54934. return FreeCameraTouchInput;
  54935. }());
  54936. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  54937. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  54938. })(BABYLON || (BABYLON = {}));
  54939. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  54940. var BABYLON;
  54941. (function (BABYLON) {
  54942. // We're mainly based on the logic defined into the FreeCamera code
  54943. var TouchCamera = /** @class */ (function (_super) {
  54944. __extends(TouchCamera, _super);
  54945. //-- end properties for backward compatibility for inputs
  54946. function TouchCamera(name, position, scene) {
  54947. var _this = _super.call(this, name, position, scene) || this;
  54948. _this.inputs.addTouch();
  54949. _this._setupInputs();
  54950. return _this;
  54951. }
  54952. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  54953. //-- Begin properties for backward compatibility for inputs
  54954. get: function () {
  54955. var touch = this.inputs.attached["touch"];
  54956. if (touch)
  54957. return touch.touchAngularSensibility;
  54958. return 0;
  54959. },
  54960. set: function (value) {
  54961. var touch = this.inputs.attached["touch"];
  54962. if (touch)
  54963. touch.touchAngularSensibility = value;
  54964. },
  54965. enumerable: true,
  54966. configurable: true
  54967. });
  54968. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  54969. get: function () {
  54970. var touch = this.inputs.attached["touch"];
  54971. if (touch)
  54972. return touch.touchMoveSensibility;
  54973. return 0;
  54974. },
  54975. set: function (value) {
  54976. var touch = this.inputs.attached["touch"];
  54977. if (touch)
  54978. touch.touchMoveSensibility = value;
  54979. },
  54980. enumerable: true,
  54981. configurable: true
  54982. });
  54983. TouchCamera.prototype.getClassName = function () {
  54984. return "TouchCamera";
  54985. };
  54986. TouchCamera.prototype._setupInputs = function () {
  54987. var mouse = this.inputs.attached["mouse"];
  54988. if (mouse) {
  54989. mouse.touchEnabled = false;
  54990. }
  54991. };
  54992. return TouchCamera;
  54993. }(BABYLON.FreeCamera));
  54994. BABYLON.TouchCamera = TouchCamera;
  54995. })(BABYLON || (BABYLON = {}));
  54996. //# sourceMappingURL=babylon.touchCamera.js.map
  54997. var BABYLON;
  54998. (function (BABYLON) {
  54999. var ProceduralTexture = /** @class */ (function (_super) {
  55000. __extends(ProceduralTexture, _super);
  55001. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  55002. if (fallbackTexture === void 0) { fallbackTexture = null; }
  55003. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55004. if (isCube === void 0) { isCube = false; }
  55005. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  55006. _this.isCube = isCube;
  55007. _this.isEnabled = true;
  55008. _this._currentRefreshId = -1;
  55009. _this._refreshRate = 1;
  55010. _this._vertexBuffers = {};
  55011. _this._uniforms = new Array();
  55012. _this._samplers = new Array();
  55013. _this._textures = {};
  55014. _this._floats = {};
  55015. _this._floatsArrays = {};
  55016. _this._colors3 = {};
  55017. _this._colors4 = {};
  55018. _this._vectors2 = {};
  55019. _this._vectors3 = {};
  55020. _this._matrices = {};
  55021. _this._fallbackTextureUsed = false;
  55022. scene._proceduralTextures.push(_this);
  55023. _this._engine = scene.getEngine();
  55024. _this.name = name;
  55025. _this.isRenderTarget = true;
  55026. _this._size = size;
  55027. _this._generateMipMaps = generateMipMaps;
  55028. _this.setFragment(fragment);
  55029. _this._fallbackTexture = fallbackTexture;
  55030. if (isCube) {
  55031. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  55032. _this.setFloat("face", 0);
  55033. }
  55034. else {
  55035. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  55036. }
  55037. // VBO
  55038. var vertices = [];
  55039. vertices.push(1, 1);
  55040. vertices.push(-1, 1);
  55041. vertices.push(-1, -1);
  55042. vertices.push(1, -1);
  55043. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  55044. _this._createIndexBuffer();
  55045. return _this;
  55046. }
  55047. ProceduralTexture.prototype._createIndexBuffer = function () {
  55048. var engine = this._engine;
  55049. // Indices
  55050. var indices = [];
  55051. indices.push(0);
  55052. indices.push(1);
  55053. indices.push(2);
  55054. indices.push(0);
  55055. indices.push(2);
  55056. indices.push(3);
  55057. this._indexBuffer = engine.createIndexBuffer(indices);
  55058. };
  55059. ProceduralTexture.prototype._rebuild = function () {
  55060. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  55061. if (vb) {
  55062. vb._rebuild();
  55063. }
  55064. this._createIndexBuffer();
  55065. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  55066. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  55067. }
  55068. };
  55069. ProceduralTexture.prototype.reset = function () {
  55070. if (this._effect === undefined) {
  55071. return;
  55072. }
  55073. var engine = this._engine;
  55074. engine._releaseEffect(this._effect);
  55075. };
  55076. ProceduralTexture.prototype.isReady = function () {
  55077. var _this = this;
  55078. var engine = this._engine;
  55079. var shaders;
  55080. if (!this._fragment) {
  55081. return false;
  55082. }
  55083. if (this._fallbackTextureUsed) {
  55084. return true;
  55085. }
  55086. if (this._fragment.fragmentElement !== undefined) {
  55087. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  55088. }
  55089. else {
  55090. shaders = { vertex: "procedural", fragment: this._fragment };
  55091. }
  55092. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  55093. _this.releaseInternalTexture();
  55094. if (_this._fallbackTexture) {
  55095. _this._texture = _this._fallbackTexture._texture;
  55096. if (_this._texture) {
  55097. _this._texture.incrementReferences();
  55098. }
  55099. }
  55100. _this._fallbackTextureUsed = true;
  55101. });
  55102. return this._effect.isReady();
  55103. };
  55104. ProceduralTexture.prototype.resetRefreshCounter = function () {
  55105. this._currentRefreshId = -1;
  55106. };
  55107. ProceduralTexture.prototype.setFragment = function (fragment) {
  55108. this._fragment = fragment;
  55109. };
  55110. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  55111. get: function () {
  55112. return this._refreshRate;
  55113. },
  55114. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  55115. set: function (value) {
  55116. this._refreshRate = value;
  55117. this.resetRefreshCounter();
  55118. },
  55119. enumerable: true,
  55120. configurable: true
  55121. });
  55122. ProceduralTexture.prototype._shouldRender = function () {
  55123. if (!this.isEnabled || !this.isReady() || !this._texture) {
  55124. return false;
  55125. }
  55126. if (this._fallbackTextureUsed) {
  55127. return false;
  55128. }
  55129. if (this._currentRefreshId === -1) {
  55130. this._currentRefreshId = 1;
  55131. return true;
  55132. }
  55133. if (this.refreshRate === this._currentRefreshId) {
  55134. this._currentRefreshId = 1;
  55135. return true;
  55136. }
  55137. this._currentRefreshId++;
  55138. return false;
  55139. };
  55140. ProceduralTexture.prototype.getRenderSize = function () {
  55141. return this._size;
  55142. };
  55143. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  55144. if (this._fallbackTextureUsed) {
  55145. return;
  55146. }
  55147. this.releaseInternalTexture();
  55148. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  55149. };
  55150. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  55151. if (this._uniforms.indexOf(uniformName) === -1) {
  55152. this._uniforms.push(uniformName);
  55153. }
  55154. };
  55155. ProceduralTexture.prototype.setTexture = function (name, texture) {
  55156. if (this._samplers.indexOf(name) === -1) {
  55157. this._samplers.push(name);
  55158. }
  55159. this._textures[name] = texture;
  55160. return this;
  55161. };
  55162. ProceduralTexture.prototype.setFloat = function (name, value) {
  55163. this._checkUniform(name);
  55164. this._floats[name] = value;
  55165. return this;
  55166. };
  55167. ProceduralTexture.prototype.setFloats = function (name, value) {
  55168. this._checkUniform(name);
  55169. this._floatsArrays[name] = value;
  55170. return this;
  55171. };
  55172. ProceduralTexture.prototype.setColor3 = function (name, value) {
  55173. this._checkUniform(name);
  55174. this._colors3[name] = value;
  55175. return this;
  55176. };
  55177. ProceduralTexture.prototype.setColor4 = function (name, value) {
  55178. this._checkUniform(name);
  55179. this._colors4[name] = value;
  55180. return this;
  55181. };
  55182. ProceduralTexture.prototype.setVector2 = function (name, value) {
  55183. this._checkUniform(name);
  55184. this._vectors2[name] = value;
  55185. return this;
  55186. };
  55187. ProceduralTexture.prototype.setVector3 = function (name, value) {
  55188. this._checkUniform(name);
  55189. this._vectors3[name] = value;
  55190. return this;
  55191. };
  55192. ProceduralTexture.prototype.setMatrix = function (name, value) {
  55193. this._checkUniform(name);
  55194. this._matrices[name] = value;
  55195. return this;
  55196. };
  55197. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  55198. var scene = this.getScene();
  55199. if (!scene) {
  55200. return;
  55201. }
  55202. var engine = this._engine;
  55203. // Render
  55204. engine.enableEffect(this._effect);
  55205. engine.setState(false);
  55206. // Texture
  55207. for (var name in this._textures) {
  55208. this._effect.setTexture(name, this._textures[name]);
  55209. }
  55210. // Float
  55211. for (name in this._floats) {
  55212. this._effect.setFloat(name, this._floats[name]);
  55213. }
  55214. // Floats
  55215. for (name in this._floatsArrays) {
  55216. this._effect.setArray(name, this._floatsArrays[name]);
  55217. }
  55218. // Color3
  55219. for (name in this._colors3) {
  55220. this._effect.setColor3(name, this._colors3[name]);
  55221. }
  55222. // Color4
  55223. for (name in this._colors4) {
  55224. var color = this._colors4[name];
  55225. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  55226. }
  55227. // Vector2
  55228. for (name in this._vectors2) {
  55229. this._effect.setVector2(name, this._vectors2[name]);
  55230. }
  55231. // Vector3
  55232. for (name in this._vectors3) {
  55233. this._effect.setVector3(name, this._vectors3[name]);
  55234. }
  55235. // Matrix
  55236. for (name in this._matrices) {
  55237. this._effect.setMatrix(name, this._matrices[name]);
  55238. }
  55239. if (!this._texture) {
  55240. return;
  55241. }
  55242. if (this.isCube) {
  55243. for (var face = 0; face < 6; face++) {
  55244. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  55245. // VBOs
  55246. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  55247. this._effect.setFloat("face", face);
  55248. // Clear
  55249. engine.clear(scene.clearColor, true, true, true);
  55250. // Draw order
  55251. engine.draw(true, 0, 6);
  55252. // Mipmaps
  55253. if (face === 5) {
  55254. engine.generateMipMapsForCubemap(this._texture);
  55255. }
  55256. }
  55257. }
  55258. else {
  55259. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  55260. // VBOs
  55261. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  55262. // Clear
  55263. engine.clear(scene.clearColor, true, true, true);
  55264. // Draw order
  55265. engine.draw(true, 0, 6);
  55266. }
  55267. // Unbind
  55268. engine.unBindFramebuffer(this._texture, this.isCube);
  55269. if (this.onGenerated) {
  55270. this.onGenerated();
  55271. }
  55272. };
  55273. ProceduralTexture.prototype.clone = function () {
  55274. var textureSize = this.getSize();
  55275. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  55276. // Base texture
  55277. newTexture.hasAlpha = this.hasAlpha;
  55278. newTexture.level = this.level;
  55279. // RenderTarget Texture
  55280. newTexture.coordinatesMode = this.coordinatesMode;
  55281. return newTexture;
  55282. };
  55283. ProceduralTexture.prototype.dispose = function () {
  55284. var scene = this.getScene();
  55285. if (!scene) {
  55286. return;
  55287. }
  55288. var index = scene._proceduralTextures.indexOf(this);
  55289. if (index >= 0) {
  55290. scene._proceduralTextures.splice(index, 1);
  55291. }
  55292. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  55293. if (vertexBuffer) {
  55294. vertexBuffer.dispose();
  55295. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  55296. }
  55297. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  55298. this._indexBuffer = null;
  55299. }
  55300. _super.prototype.dispose.call(this);
  55301. };
  55302. return ProceduralTexture;
  55303. }(BABYLON.Texture));
  55304. BABYLON.ProceduralTexture = ProceduralTexture;
  55305. })(BABYLON || (BABYLON = {}));
  55306. //# sourceMappingURL=babylon.proceduralTexture.js.map
  55307. var BABYLON;
  55308. (function (BABYLON) {
  55309. var CustomProceduralTexture = /** @class */ (function (_super) {
  55310. __extends(CustomProceduralTexture, _super);
  55311. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  55312. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  55313. _this._animate = true;
  55314. _this._time = 0;
  55315. _this._texturePath = texturePath;
  55316. //Try to load json
  55317. _this.loadJson(texturePath);
  55318. _this.refreshRate = 1;
  55319. return _this;
  55320. }
  55321. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  55322. var _this = this;
  55323. var noConfigFile = function () {
  55324. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  55325. try {
  55326. _this.setFragment(_this._texturePath);
  55327. }
  55328. catch (ex) {
  55329. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  55330. }
  55331. };
  55332. var configFileUrl = jsonUrl + "/config.json";
  55333. var xhr = new XMLHttpRequest();
  55334. xhr.open("GET", configFileUrl, true);
  55335. xhr.addEventListener("load", function () {
  55336. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  55337. try {
  55338. _this._config = JSON.parse(xhr.response);
  55339. _this.updateShaderUniforms();
  55340. _this.updateTextures();
  55341. _this.setFragment(_this._texturePath + "/custom");
  55342. _this._animate = _this._config.animate;
  55343. _this.refreshRate = _this._config.refreshrate;
  55344. }
  55345. catch (ex) {
  55346. noConfigFile();
  55347. }
  55348. }
  55349. else {
  55350. noConfigFile();
  55351. }
  55352. }, false);
  55353. xhr.addEventListener("error", function () {
  55354. noConfigFile();
  55355. }, false);
  55356. try {
  55357. xhr.send();
  55358. }
  55359. catch (ex) {
  55360. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  55361. }
  55362. };
  55363. CustomProceduralTexture.prototype.isReady = function () {
  55364. if (!_super.prototype.isReady.call(this)) {
  55365. return false;
  55366. }
  55367. for (var name in this._textures) {
  55368. var texture = this._textures[name];
  55369. if (!texture.isReady()) {
  55370. return false;
  55371. }
  55372. }
  55373. return true;
  55374. };
  55375. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  55376. var scene = this.getScene();
  55377. if (this._animate && scene) {
  55378. this._time += scene.getAnimationRatio() * 0.03;
  55379. this.updateShaderUniforms();
  55380. }
  55381. _super.prototype.render.call(this, useCameraPostProcess);
  55382. };
  55383. CustomProceduralTexture.prototype.updateTextures = function () {
  55384. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  55385. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  55386. }
  55387. };
  55388. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  55389. if (this._config) {
  55390. for (var j = 0; j < this._config.uniforms.length; j++) {
  55391. var uniform = this._config.uniforms[j];
  55392. switch (uniform.type) {
  55393. case "float":
  55394. this.setFloat(uniform.name, uniform.value);
  55395. break;
  55396. case "color3":
  55397. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  55398. break;
  55399. case "color4":
  55400. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  55401. break;
  55402. case "vector2":
  55403. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  55404. break;
  55405. case "vector3":
  55406. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  55407. break;
  55408. }
  55409. }
  55410. }
  55411. this.setFloat("time", this._time);
  55412. };
  55413. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  55414. get: function () {
  55415. return this._animate;
  55416. },
  55417. set: function (value) {
  55418. this._animate = value;
  55419. },
  55420. enumerable: true,
  55421. configurable: true
  55422. });
  55423. return CustomProceduralTexture;
  55424. }(BABYLON.ProceduralTexture));
  55425. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  55426. })(BABYLON || (BABYLON = {}));
  55427. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  55428. var BABYLON;
  55429. (function (BABYLON) {
  55430. var FreeCameraGamepadInput = /** @class */ (function () {
  55431. function FreeCameraGamepadInput() {
  55432. this.gamepadAngularSensibility = 200;
  55433. this.gamepadMoveSensibility = 40;
  55434. // private members
  55435. this._cameraTransform = BABYLON.Matrix.Identity();
  55436. this._deltaTransform = BABYLON.Vector3.Zero();
  55437. this._vector3 = BABYLON.Vector3.Zero();
  55438. this._vector2 = BABYLON.Vector2.Zero();
  55439. }
  55440. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  55441. var _this = this;
  55442. var manager = this.camera.getScene().gamepadManager;
  55443. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  55444. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  55445. // prioritize XBOX gamepads.
  55446. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  55447. _this.gamepad = gamepad;
  55448. }
  55449. }
  55450. });
  55451. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  55452. if (_this.gamepad === gamepad) {
  55453. _this.gamepad = null;
  55454. }
  55455. });
  55456. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  55457. };
  55458. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  55459. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  55460. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  55461. this.gamepad = null;
  55462. };
  55463. FreeCameraGamepadInput.prototype.checkInputs = function () {
  55464. if (this.gamepad && this.gamepad.leftStick) {
  55465. var camera = this.camera;
  55466. var LSValues = this.gamepad.leftStick;
  55467. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  55468. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  55469. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  55470. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  55471. var RSValues = this.gamepad.rightStick;
  55472. if (RSValues) {
  55473. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  55474. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  55475. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  55476. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  55477. }
  55478. else {
  55479. RSValues = { x: 0, y: 0 };
  55480. }
  55481. if (!camera.rotationQuaternion) {
  55482. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  55483. }
  55484. else {
  55485. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  55486. }
  55487. var speed = camera._computeLocalCameraSpeed() * 50.0;
  55488. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  55489. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  55490. camera.cameraDirection.addInPlace(this._deltaTransform);
  55491. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  55492. camera.cameraRotation.addInPlace(this._vector2);
  55493. }
  55494. };
  55495. FreeCameraGamepadInput.prototype.getClassName = function () {
  55496. return "FreeCameraGamepadInput";
  55497. };
  55498. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  55499. return "gamepad";
  55500. };
  55501. __decorate([
  55502. BABYLON.serialize()
  55503. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  55504. __decorate([
  55505. BABYLON.serialize()
  55506. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  55507. return FreeCameraGamepadInput;
  55508. }());
  55509. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  55510. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  55511. })(BABYLON || (BABYLON = {}));
  55512. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  55513. var BABYLON;
  55514. (function (BABYLON) {
  55515. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  55516. function ArcRotateCameraGamepadInput() {
  55517. this.gamepadRotationSensibility = 80;
  55518. this.gamepadMoveSensibility = 40;
  55519. }
  55520. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  55521. var _this = this;
  55522. var manager = this.camera.getScene().gamepadManager;
  55523. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  55524. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  55525. // prioritize XBOX gamepads.
  55526. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  55527. _this.gamepad = gamepad;
  55528. }
  55529. }
  55530. });
  55531. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  55532. if (_this.gamepad === gamepad) {
  55533. _this.gamepad = null;
  55534. }
  55535. });
  55536. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  55537. };
  55538. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  55539. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  55540. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  55541. this.gamepad = null;
  55542. };
  55543. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  55544. if (this.gamepad) {
  55545. var camera = this.camera;
  55546. var RSValues = this.gamepad.rightStick;
  55547. if (RSValues) {
  55548. if (RSValues.x != 0) {
  55549. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  55550. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  55551. camera.inertialAlphaOffset += normalizedRX;
  55552. }
  55553. }
  55554. if (RSValues.y != 0) {
  55555. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  55556. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  55557. camera.inertialBetaOffset += normalizedRY;
  55558. }
  55559. }
  55560. }
  55561. var LSValues = this.gamepad.leftStick;
  55562. if (LSValues && LSValues.y != 0) {
  55563. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  55564. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  55565. this.camera.inertialRadiusOffset -= normalizedLY;
  55566. }
  55567. }
  55568. }
  55569. };
  55570. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  55571. return "ArcRotateCameraGamepadInput";
  55572. };
  55573. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  55574. return "gamepad";
  55575. };
  55576. __decorate([
  55577. BABYLON.serialize()
  55578. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  55579. __decorate([
  55580. BABYLON.serialize()
  55581. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  55582. return ArcRotateCameraGamepadInput;
  55583. }());
  55584. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  55585. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  55586. })(BABYLON || (BABYLON = {}));
  55587. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  55588. var BABYLON;
  55589. (function (BABYLON) {
  55590. var GamepadManager = /** @class */ (function () {
  55591. function GamepadManager() {
  55592. var _this = this;
  55593. this._babylonGamepads = [];
  55594. this._oneGamepadConnected = false;
  55595. this._isMonitoring = false;
  55596. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  55597. if (!BABYLON.Tools.IsWindowObjectExist()) {
  55598. this._gamepadEventSupported = false;
  55599. }
  55600. else {
  55601. this._gamepadEventSupported = 'GamepadEvent' in window;
  55602. this._gamepadSupport = (navigator.getGamepads ||
  55603. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  55604. }
  55605. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  55606. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  55607. for (var i in _this._babylonGamepads) {
  55608. var gamepad = _this._babylonGamepads[i];
  55609. if (gamepad && gamepad._isConnected) {
  55610. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  55611. }
  55612. }
  55613. });
  55614. this._onGamepadConnectedEvent = function (evt) {
  55615. var gamepad = evt.gamepad;
  55616. if (gamepad.index in _this._babylonGamepads) {
  55617. if (_this._babylonGamepads[gamepad.index].isConnected) {
  55618. return;
  55619. }
  55620. }
  55621. var newGamepad;
  55622. if (_this._babylonGamepads[gamepad.index]) {
  55623. newGamepad = _this._babylonGamepads[gamepad.index];
  55624. newGamepad.browserGamepad = gamepad;
  55625. newGamepad._isConnected = true;
  55626. }
  55627. else {
  55628. newGamepad = _this._addNewGamepad(gamepad);
  55629. }
  55630. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  55631. _this._startMonitoringGamepads();
  55632. };
  55633. this._onGamepadDisconnectedEvent = function (evt) {
  55634. var gamepad = evt.gamepad;
  55635. // Remove the gamepad from the list of gamepads to monitor.
  55636. for (var i in _this._babylonGamepads) {
  55637. if (_this._babylonGamepads[i].index === gamepad.index) {
  55638. var disconnectedGamepad = _this._babylonGamepads[i];
  55639. disconnectedGamepad._isConnected = false;
  55640. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  55641. break;
  55642. }
  55643. }
  55644. };
  55645. if (this._gamepadSupport) {
  55646. //first add already-connected gamepads
  55647. this._updateGamepadObjects();
  55648. if (this._babylonGamepads.length) {
  55649. this._startMonitoringGamepads();
  55650. }
  55651. // Checking if the gamepad connected event is supported (like in Firefox)
  55652. if (this._gamepadEventSupported) {
  55653. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  55654. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  55655. }
  55656. else {
  55657. this._startMonitoringGamepads();
  55658. }
  55659. }
  55660. }
  55661. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  55662. get: function () {
  55663. return this._babylonGamepads;
  55664. },
  55665. enumerable: true,
  55666. configurable: true
  55667. });
  55668. GamepadManager.prototype.getGamepadByType = function (type) {
  55669. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  55670. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  55671. var gamepad = _a[_i];
  55672. if (gamepad && gamepad.type === type) {
  55673. return gamepad;
  55674. }
  55675. }
  55676. return null;
  55677. };
  55678. GamepadManager.prototype.dispose = function () {
  55679. if (this._gamepadEventSupported) {
  55680. if (this._onGamepadConnectedEvent) {
  55681. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  55682. }
  55683. if (this._onGamepadDisconnectedEvent) {
  55684. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  55685. }
  55686. this._onGamepadConnectedEvent = null;
  55687. this._onGamepadDisconnectedEvent = null;
  55688. }
  55689. this._babylonGamepads.forEach(function (gamepad) {
  55690. gamepad.dispose();
  55691. });
  55692. this.onGamepadConnectedObservable.clear();
  55693. this.onGamepadDisconnectedObservable.clear();
  55694. this._oneGamepadConnected = false;
  55695. this._stopMonitoringGamepads();
  55696. this._babylonGamepads = [];
  55697. };
  55698. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  55699. if (!this._oneGamepadConnected) {
  55700. this._oneGamepadConnected = true;
  55701. }
  55702. var newGamepad;
  55703. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  55704. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  55705. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  55706. }
  55707. else if (gamepad.pose) {
  55708. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  55709. }
  55710. else {
  55711. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  55712. }
  55713. this._babylonGamepads[newGamepad.index] = newGamepad;
  55714. return newGamepad;
  55715. };
  55716. GamepadManager.prototype._startMonitoringGamepads = function () {
  55717. if (!this._isMonitoring) {
  55718. this._isMonitoring = true;
  55719. this._checkGamepadsStatus();
  55720. }
  55721. };
  55722. GamepadManager.prototype._stopMonitoringGamepads = function () {
  55723. this._isMonitoring = false;
  55724. };
  55725. GamepadManager.prototype._checkGamepadsStatus = function () {
  55726. var _this = this;
  55727. // Hack to be compatible Chrome
  55728. this._updateGamepadObjects();
  55729. for (var i in this._babylonGamepads) {
  55730. var gamepad = this._babylonGamepads[i];
  55731. if (!gamepad || !gamepad.isConnected) {
  55732. continue;
  55733. }
  55734. gamepad.update();
  55735. }
  55736. if (this._isMonitoring) {
  55737. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  55738. }
  55739. };
  55740. // This function is called only on Chrome, which does not properly support
  55741. // connection/disconnection events and forces you to recopy again the gamepad object
  55742. GamepadManager.prototype._updateGamepadObjects = function () {
  55743. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  55744. for (var i = 0; i < gamepads.length; i++) {
  55745. if (gamepads[i]) {
  55746. if (!this._babylonGamepads[gamepads[i].index]) {
  55747. var newGamepad = this._addNewGamepad(gamepads[i]);
  55748. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  55749. }
  55750. else {
  55751. // Forced to copy again this object for Chrome for unknown reason
  55752. this._babylonGamepads[i].browserGamepad = gamepads[i];
  55753. if (!this._babylonGamepads[i].isConnected) {
  55754. this._babylonGamepads[i]._isConnected = true;
  55755. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  55756. }
  55757. }
  55758. }
  55759. }
  55760. };
  55761. return GamepadManager;
  55762. }());
  55763. BABYLON.GamepadManager = GamepadManager;
  55764. })(BABYLON || (BABYLON = {}));
  55765. //# sourceMappingURL=babylon.gamepadManager.js.map
  55766. var BABYLON;
  55767. (function (BABYLON) {
  55768. var StickValues = /** @class */ (function () {
  55769. function StickValues(x, y) {
  55770. this.x = x;
  55771. this.y = y;
  55772. }
  55773. return StickValues;
  55774. }());
  55775. BABYLON.StickValues = StickValues;
  55776. var Gamepad = /** @class */ (function () {
  55777. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  55778. if (leftStickX === void 0) { leftStickX = 0; }
  55779. if (leftStickY === void 0) { leftStickY = 1; }
  55780. if (rightStickX === void 0) { rightStickX = 2; }
  55781. if (rightStickY === void 0) { rightStickY = 3; }
  55782. this.id = id;
  55783. this.index = index;
  55784. this.browserGamepad = browserGamepad;
  55785. this._isConnected = true;
  55786. this.type = Gamepad.GAMEPAD;
  55787. this._leftStickAxisX = leftStickX;
  55788. this._leftStickAxisY = leftStickY;
  55789. this._rightStickAxisX = rightStickX;
  55790. this._rightStickAxisY = rightStickY;
  55791. if (this.browserGamepad.axes.length >= 2) {
  55792. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  55793. }
  55794. if (this.browserGamepad.axes.length >= 4) {
  55795. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  55796. }
  55797. }
  55798. Object.defineProperty(Gamepad.prototype, "isConnected", {
  55799. get: function () {
  55800. return this._isConnected;
  55801. },
  55802. enumerable: true,
  55803. configurable: true
  55804. });
  55805. Gamepad.prototype.onleftstickchanged = function (callback) {
  55806. this._onleftstickchanged = callback;
  55807. };
  55808. Gamepad.prototype.onrightstickchanged = function (callback) {
  55809. this._onrightstickchanged = callback;
  55810. };
  55811. Object.defineProperty(Gamepad.prototype, "leftStick", {
  55812. get: function () {
  55813. return this._leftStick;
  55814. },
  55815. set: function (newValues) {
  55816. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  55817. this._onleftstickchanged(newValues);
  55818. }
  55819. this._leftStick = newValues;
  55820. },
  55821. enumerable: true,
  55822. configurable: true
  55823. });
  55824. Object.defineProperty(Gamepad.prototype, "rightStick", {
  55825. get: function () {
  55826. return this._rightStick;
  55827. },
  55828. set: function (newValues) {
  55829. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  55830. this._onrightstickchanged(newValues);
  55831. }
  55832. this._rightStick = newValues;
  55833. },
  55834. enumerable: true,
  55835. configurable: true
  55836. });
  55837. Gamepad.prototype.update = function () {
  55838. if (this._leftStick) {
  55839. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  55840. }
  55841. if (this._rightStick) {
  55842. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  55843. }
  55844. };
  55845. Gamepad.prototype.dispose = function () {
  55846. };
  55847. Gamepad.GAMEPAD = 0;
  55848. Gamepad.GENERIC = 1;
  55849. Gamepad.XBOX = 2;
  55850. Gamepad.POSE_ENABLED = 3;
  55851. return Gamepad;
  55852. }());
  55853. BABYLON.Gamepad = Gamepad;
  55854. var GenericPad = /** @class */ (function (_super) {
  55855. __extends(GenericPad, _super);
  55856. function GenericPad(id, index, browserGamepad) {
  55857. var _this = _super.call(this, id, index, browserGamepad) || this;
  55858. _this.onButtonDownObservable = new BABYLON.Observable();
  55859. _this.onButtonUpObservable = new BABYLON.Observable();
  55860. _this.type = Gamepad.GENERIC;
  55861. _this._buttons = new Array(browserGamepad.buttons.length);
  55862. return _this;
  55863. }
  55864. GenericPad.prototype.onbuttondown = function (callback) {
  55865. this._onbuttondown = callback;
  55866. };
  55867. GenericPad.prototype.onbuttonup = function (callback) {
  55868. this._onbuttonup = callback;
  55869. };
  55870. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  55871. if (newValue !== currentValue) {
  55872. if (newValue === 1) {
  55873. if (this._onbuttondown) {
  55874. this._onbuttondown(buttonIndex);
  55875. }
  55876. this.onButtonDownObservable.notifyObservers(buttonIndex);
  55877. }
  55878. if (newValue === 0) {
  55879. if (this._onbuttonup) {
  55880. this._onbuttonup(buttonIndex);
  55881. }
  55882. this.onButtonUpObservable.notifyObservers(buttonIndex);
  55883. }
  55884. }
  55885. return newValue;
  55886. };
  55887. GenericPad.prototype.update = function () {
  55888. _super.prototype.update.call(this);
  55889. for (var index = 0; index < this._buttons.length; index++) {
  55890. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  55891. }
  55892. };
  55893. return GenericPad;
  55894. }(Gamepad));
  55895. BABYLON.GenericPad = GenericPad;
  55896. })(BABYLON || (BABYLON = {}));
  55897. //# sourceMappingURL=babylon.gamepad.js.map
  55898. var BABYLON;
  55899. (function (BABYLON) {
  55900. var Xbox360Button;
  55901. (function (Xbox360Button) {
  55902. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  55903. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  55904. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  55905. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  55906. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  55907. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  55908. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  55909. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  55910. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  55911. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  55912. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  55913. var Xbox360Dpad;
  55914. (function (Xbox360Dpad) {
  55915. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  55916. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  55917. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  55918. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  55919. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  55920. var Xbox360Pad = /** @class */ (function (_super) {
  55921. __extends(Xbox360Pad, _super);
  55922. function Xbox360Pad(id, index, gamepad, xboxOne) {
  55923. if (xboxOne === void 0) { xboxOne = false; }
  55924. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  55925. _this._leftTrigger = 0;
  55926. _this._rightTrigger = 0;
  55927. _this.onButtonDownObservable = new BABYLON.Observable();
  55928. _this.onButtonUpObservable = new BABYLON.Observable();
  55929. _this.onPadDownObservable = new BABYLON.Observable();
  55930. _this.onPadUpObservable = new BABYLON.Observable();
  55931. _this._buttonA = 0;
  55932. _this._buttonB = 0;
  55933. _this._buttonX = 0;
  55934. _this._buttonY = 0;
  55935. _this._buttonBack = 0;
  55936. _this._buttonStart = 0;
  55937. _this._buttonLB = 0;
  55938. _this._buttonRB = 0;
  55939. _this._buttonLeftStick = 0;
  55940. _this._buttonRightStick = 0;
  55941. _this._dPadUp = 0;
  55942. _this._dPadDown = 0;
  55943. _this._dPadLeft = 0;
  55944. _this._dPadRight = 0;
  55945. _this._isXboxOnePad = false;
  55946. _this.type = BABYLON.Gamepad.XBOX;
  55947. _this._isXboxOnePad = xboxOne;
  55948. return _this;
  55949. }
  55950. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  55951. this._onlefttriggerchanged = callback;
  55952. };
  55953. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  55954. this._onrighttriggerchanged = callback;
  55955. };
  55956. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  55957. get: function () {
  55958. return this._leftTrigger;
  55959. },
  55960. set: function (newValue) {
  55961. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  55962. this._onlefttriggerchanged(newValue);
  55963. }
  55964. this._leftTrigger = newValue;
  55965. },
  55966. enumerable: true,
  55967. configurable: true
  55968. });
  55969. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  55970. get: function () {
  55971. return this._rightTrigger;
  55972. },
  55973. set: function (newValue) {
  55974. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  55975. this._onrighttriggerchanged(newValue);
  55976. }
  55977. this._rightTrigger = newValue;
  55978. },
  55979. enumerable: true,
  55980. configurable: true
  55981. });
  55982. Xbox360Pad.prototype.onbuttondown = function (callback) {
  55983. this._onbuttondown = callback;
  55984. };
  55985. Xbox360Pad.prototype.onbuttonup = function (callback) {
  55986. this._onbuttonup = callback;
  55987. };
  55988. Xbox360Pad.prototype.ondpaddown = function (callback) {
  55989. this._ondpaddown = callback;
  55990. };
  55991. Xbox360Pad.prototype.ondpadup = function (callback) {
  55992. this._ondpadup = callback;
  55993. };
  55994. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  55995. if (newValue !== currentValue) {
  55996. if (newValue === 1) {
  55997. if (this._onbuttondown) {
  55998. this._onbuttondown(buttonType);
  55999. }
  56000. this.onButtonDownObservable.notifyObservers(buttonType);
  56001. }
  56002. if (newValue === 0) {
  56003. if (this._onbuttonup) {
  56004. this._onbuttonup(buttonType);
  56005. }
  56006. this.onButtonUpObservable.notifyObservers(buttonType);
  56007. }
  56008. }
  56009. return newValue;
  56010. };
  56011. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  56012. if (newValue !== currentValue) {
  56013. if (newValue === 1) {
  56014. if (this._ondpaddown) {
  56015. this._ondpaddown(buttonType);
  56016. }
  56017. this.onPadDownObservable.notifyObservers(buttonType);
  56018. }
  56019. if (newValue === 0) {
  56020. if (this._ondpadup) {
  56021. this._ondpadup(buttonType);
  56022. }
  56023. this.onPadUpObservable.notifyObservers(buttonType);
  56024. }
  56025. }
  56026. return newValue;
  56027. };
  56028. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  56029. get: function () {
  56030. return this._buttonA;
  56031. },
  56032. set: function (value) {
  56033. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  56034. },
  56035. enumerable: true,
  56036. configurable: true
  56037. });
  56038. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  56039. get: function () {
  56040. return this._buttonB;
  56041. },
  56042. set: function (value) {
  56043. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  56044. },
  56045. enumerable: true,
  56046. configurable: true
  56047. });
  56048. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  56049. get: function () {
  56050. return this._buttonX;
  56051. },
  56052. set: function (value) {
  56053. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  56054. },
  56055. enumerable: true,
  56056. configurable: true
  56057. });
  56058. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  56059. get: function () {
  56060. return this._buttonY;
  56061. },
  56062. set: function (value) {
  56063. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  56064. },
  56065. enumerable: true,
  56066. configurable: true
  56067. });
  56068. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  56069. get: function () {
  56070. return this._buttonStart;
  56071. },
  56072. set: function (value) {
  56073. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  56074. },
  56075. enumerable: true,
  56076. configurable: true
  56077. });
  56078. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  56079. get: function () {
  56080. return this._buttonBack;
  56081. },
  56082. set: function (value) {
  56083. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  56084. },
  56085. enumerable: true,
  56086. configurable: true
  56087. });
  56088. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  56089. get: function () {
  56090. return this._buttonLB;
  56091. },
  56092. set: function (value) {
  56093. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  56094. },
  56095. enumerable: true,
  56096. configurable: true
  56097. });
  56098. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  56099. get: function () {
  56100. return this._buttonRB;
  56101. },
  56102. set: function (value) {
  56103. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  56104. },
  56105. enumerable: true,
  56106. configurable: true
  56107. });
  56108. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  56109. get: function () {
  56110. return this._buttonLeftStick;
  56111. },
  56112. set: function (value) {
  56113. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  56114. },
  56115. enumerable: true,
  56116. configurable: true
  56117. });
  56118. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  56119. get: function () {
  56120. return this._buttonRightStick;
  56121. },
  56122. set: function (value) {
  56123. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  56124. },
  56125. enumerable: true,
  56126. configurable: true
  56127. });
  56128. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  56129. get: function () {
  56130. return this._dPadUp;
  56131. },
  56132. set: function (value) {
  56133. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  56134. },
  56135. enumerable: true,
  56136. configurable: true
  56137. });
  56138. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  56139. get: function () {
  56140. return this._dPadDown;
  56141. },
  56142. set: function (value) {
  56143. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  56144. },
  56145. enumerable: true,
  56146. configurable: true
  56147. });
  56148. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  56149. get: function () {
  56150. return this._dPadLeft;
  56151. },
  56152. set: function (value) {
  56153. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  56154. },
  56155. enumerable: true,
  56156. configurable: true
  56157. });
  56158. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  56159. get: function () {
  56160. return this._dPadRight;
  56161. },
  56162. set: function (value) {
  56163. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  56164. },
  56165. enumerable: true,
  56166. configurable: true
  56167. });
  56168. Xbox360Pad.prototype.update = function () {
  56169. _super.prototype.update.call(this);
  56170. if (this._isXboxOnePad) {
  56171. this.buttonA = this.browserGamepad.buttons[0].value;
  56172. this.buttonB = this.browserGamepad.buttons[1].value;
  56173. this.buttonX = this.browserGamepad.buttons[2].value;
  56174. this.buttonY = this.browserGamepad.buttons[3].value;
  56175. this.buttonLB = this.browserGamepad.buttons[4].value;
  56176. this.buttonRB = this.browserGamepad.buttons[5].value;
  56177. this.leftTrigger = this.browserGamepad.axes[2];
  56178. this.rightTrigger = this.browserGamepad.axes[5];
  56179. this.buttonBack = this.browserGamepad.buttons[9].value;
  56180. this.buttonStart = this.browserGamepad.buttons[8].value;
  56181. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  56182. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  56183. this.dPadUp = this.browserGamepad.buttons[11].value;
  56184. this.dPadDown = this.browserGamepad.buttons[12].value;
  56185. this.dPadLeft = this.browserGamepad.buttons[13].value;
  56186. this.dPadRight = this.browserGamepad.buttons[14].value;
  56187. }
  56188. else {
  56189. this.buttonA = this.browserGamepad.buttons[0].value;
  56190. this.buttonB = this.browserGamepad.buttons[1].value;
  56191. this.buttonX = this.browserGamepad.buttons[2].value;
  56192. this.buttonY = this.browserGamepad.buttons[3].value;
  56193. this.buttonLB = this.browserGamepad.buttons[4].value;
  56194. this.buttonRB = this.browserGamepad.buttons[5].value;
  56195. this.leftTrigger = this.browserGamepad.buttons[6].value;
  56196. this.rightTrigger = this.browserGamepad.buttons[7].value;
  56197. this.buttonBack = this.browserGamepad.buttons[8].value;
  56198. this.buttonStart = this.browserGamepad.buttons[9].value;
  56199. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  56200. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  56201. this.dPadUp = this.browserGamepad.buttons[12].value;
  56202. this.dPadDown = this.browserGamepad.buttons[13].value;
  56203. this.dPadLeft = this.browserGamepad.buttons[14].value;
  56204. this.dPadRight = this.browserGamepad.buttons[15].value;
  56205. }
  56206. };
  56207. return Xbox360Pad;
  56208. }(BABYLON.Gamepad));
  56209. BABYLON.Xbox360Pad = Xbox360Pad;
  56210. })(BABYLON || (BABYLON = {}));
  56211. //# sourceMappingURL=babylon.xboxGamepad.js.map
  56212. var BABYLON;
  56213. (function (BABYLON) {
  56214. var PoseEnabledControllerType;
  56215. (function (PoseEnabledControllerType) {
  56216. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  56217. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  56218. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  56219. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  56220. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  56221. var PoseEnabledControllerHelper = /** @class */ (function () {
  56222. function PoseEnabledControllerHelper() {
  56223. }
  56224. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  56225. // Oculus Touch
  56226. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  56227. return new BABYLON.OculusTouchController(vrGamepad);
  56228. }
  56229. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  56230. return new BABYLON.WindowsMotionController(vrGamepad);
  56231. }
  56232. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  56233. return new BABYLON.ViveController(vrGamepad);
  56234. }
  56235. else {
  56236. return new BABYLON.GenericController(vrGamepad);
  56237. }
  56238. };
  56239. return PoseEnabledControllerHelper;
  56240. }());
  56241. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  56242. var PoseEnabledController = /** @class */ (function (_super) {
  56243. __extends(PoseEnabledController, _super);
  56244. function PoseEnabledController(browserGamepad) {
  56245. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  56246. _this.deviceScaleFactor = 1;
  56247. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  56248. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  56249. _this.controllerType = PoseEnabledControllerType.GENERIC;
  56250. _this.position = BABYLON.Vector3.Zero();
  56251. _this.rotationQuaternion = new BABYLON.Quaternion();
  56252. _this.devicePosition = BABYLON.Vector3.Zero();
  56253. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  56254. _this._calculatedPosition = BABYLON.Vector3.Zero();
  56255. _this._calculatedRotation = new BABYLON.Quaternion();
  56256. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  56257. return _this;
  56258. }
  56259. PoseEnabledController.prototype.update = function () {
  56260. _super.prototype.update.call(this);
  56261. var pose = this.browserGamepad.pose;
  56262. this.updateFromDevice(pose);
  56263. if (this._mesh) {
  56264. this._mesh.position.copyFrom(this._calculatedPosition);
  56265. if (this._mesh.rotationQuaternion) {
  56266. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  56267. }
  56268. }
  56269. };
  56270. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  56271. if (poseData) {
  56272. this.rawPose = poseData;
  56273. if (poseData.position) {
  56274. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  56275. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  56276. this.devicePosition.z *= -1;
  56277. }
  56278. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  56279. this._calculatedPosition.addInPlace(this.position);
  56280. }
  56281. var pose = this.rawPose;
  56282. if (poseData.orientation && pose.orientation) {
  56283. this.deviceRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  56284. if (this._mesh) {
  56285. if (this._mesh.getScene().useRightHandedSystem) {
  56286. this.deviceRotationQuaternion.z *= -1;
  56287. this.deviceRotationQuaternion.w *= -1;
  56288. }
  56289. else {
  56290. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  56291. }
  56292. }
  56293. // if the camera is set, rotate to the camera's rotation
  56294. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  56295. }
  56296. }
  56297. };
  56298. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  56299. if (this._mesh) {
  56300. this._mesh.parent = null;
  56301. }
  56302. this._mesh = mesh;
  56303. if (this._poseControlledCamera) {
  56304. this._mesh.parent = this._poseControlledCamera;
  56305. }
  56306. if (!this._mesh.rotationQuaternion) {
  56307. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  56308. }
  56309. };
  56310. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  56311. this._poseControlledCamera = camera;
  56312. if (this._mesh) {
  56313. this._mesh.parent = this._poseControlledCamera;
  56314. }
  56315. };
  56316. PoseEnabledController.prototype.dispose = function () {
  56317. if (this._mesh) {
  56318. this._mesh.dispose();
  56319. }
  56320. this._mesh = null;
  56321. _super.prototype.dispose.call(this);
  56322. };
  56323. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  56324. get: function () {
  56325. return this._mesh;
  56326. },
  56327. enumerable: true,
  56328. configurable: true
  56329. });
  56330. PoseEnabledController.prototype.getForwardRay = function (length) {
  56331. if (length === void 0) { length = 100; }
  56332. if (!this.mesh) {
  56333. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  56334. }
  56335. var m = this.mesh.getWorldMatrix();
  56336. var origin = m.getTranslation();
  56337. var forward = new BABYLON.Vector3(0, 0, -1);
  56338. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  56339. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  56340. return new BABYLON.Ray(origin, direction, length);
  56341. };
  56342. return PoseEnabledController;
  56343. }(BABYLON.Gamepad));
  56344. BABYLON.PoseEnabledController = PoseEnabledController;
  56345. })(BABYLON || (BABYLON = {}));
  56346. //# sourceMappingURL=babylon.poseEnabledController.js.map
  56347. var BABYLON;
  56348. (function (BABYLON) {
  56349. var WebVRController = /** @class */ (function (_super) {
  56350. __extends(WebVRController, _super);
  56351. function WebVRController(vrGamepad) {
  56352. var _this = _super.call(this, vrGamepad) || this;
  56353. // Observables
  56354. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  56355. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  56356. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  56357. _this.onPadStateChangedObservable = new BABYLON.Observable();
  56358. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  56359. _this.pad = { x: 0, y: 0 };
  56360. // avoid GC, store state in a tmp object
  56361. _this._changes = {
  56362. pressChanged: false,
  56363. touchChanged: false,
  56364. valueChanged: false,
  56365. changed: false
  56366. };
  56367. _this._buttons = new Array(vrGamepad.buttons.length);
  56368. _this.hand = vrGamepad.hand;
  56369. return _this;
  56370. }
  56371. WebVRController.prototype.onButtonStateChange = function (callback) {
  56372. this._onButtonStateChange = callback;
  56373. };
  56374. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  56375. get: function () {
  56376. return this._defaultModel;
  56377. },
  56378. enumerable: true,
  56379. configurable: true
  56380. });
  56381. WebVRController.prototype.update = function () {
  56382. _super.prototype.update.call(this);
  56383. for (var index = 0; index < this._buttons.length; index++) {
  56384. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  56385. }
  56386. ;
  56387. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  56388. this.pad.x = this.leftStick.x;
  56389. this.pad.y = this.leftStick.y;
  56390. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  56391. }
  56392. };
  56393. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  56394. if (!newState) {
  56395. newState = {
  56396. pressed: false,
  56397. touched: false,
  56398. value: 0
  56399. };
  56400. }
  56401. if (!currentState) {
  56402. this._buttons[buttonIndex] = {
  56403. pressed: newState.pressed,
  56404. touched: newState.touched,
  56405. value: newState.value
  56406. };
  56407. return;
  56408. }
  56409. this._checkChanges(newState, currentState);
  56410. if (this._changes.changed) {
  56411. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  56412. this.handleButtonChange(buttonIndex, newState, this._changes);
  56413. }
  56414. this._buttons[buttonIndex].pressed = newState.pressed;
  56415. this._buttons[buttonIndex].touched = newState.touched;
  56416. // oculus triggers are never 0, thou not touched.
  56417. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  56418. };
  56419. WebVRController.prototype._checkChanges = function (newState, currentState) {
  56420. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  56421. this._changes.touchChanged = newState.touched !== currentState.touched;
  56422. this._changes.valueChanged = newState.value !== currentState.value;
  56423. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  56424. return this._changes;
  56425. };
  56426. WebVRController.prototype.dispose = function () {
  56427. _super.prototype.dispose.call(this);
  56428. this.onTriggerStateChangedObservable.clear();
  56429. this.onMainButtonStateChangedObservable.clear();
  56430. this.onSecondaryButtonStateChangedObservable.clear();
  56431. this.onPadStateChangedObservable.clear();
  56432. this.onPadValuesChangedObservable.clear();
  56433. };
  56434. return WebVRController;
  56435. }(BABYLON.PoseEnabledController));
  56436. BABYLON.WebVRController = WebVRController;
  56437. })(BABYLON || (BABYLON = {}));
  56438. //# sourceMappingURL=babylon.webVRController.js.map
  56439. var BABYLON;
  56440. (function (BABYLON) {
  56441. var OculusTouchController = /** @class */ (function (_super) {
  56442. __extends(OculusTouchController, _super);
  56443. function OculusTouchController(vrGamepad) {
  56444. var _this = _super.call(this, vrGamepad) || this;
  56445. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  56446. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  56447. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  56448. return _this;
  56449. }
  56450. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  56451. var _this = this;
  56452. var meshName;
  56453. // Hand
  56454. if (this.hand === 'left') {
  56455. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  56456. }
  56457. else {
  56458. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  56459. }
  56460. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  56461. /*
  56462. Parent Mesh name: oculus_touch_left
  56463. - body
  56464. - trigger
  56465. - thumbstick
  56466. - grip
  56467. - button_y
  56468. - button_x
  56469. - button_enter
  56470. */
  56471. _this._defaultModel = newMeshes[1];
  56472. _this.attachToMesh(_this._defaultModel);
  56473. if (meshLoaded) {
  56474. meshLoaded(_this._defaultModel);
  56475. }
  56476. });
  56477. };
  56478. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  56479. // helper getters for left and right hand.
  56480. get: function () {
  56481. if (this.hand === 'right') {
  56482. return this.onMainButtonStateChangedObservable;
  56483. }
  56484. else {
  56485. throw new Error('No A button on left hand');
  56486. }
  56487. },
  56488. enumerable: true,
  56489. configurable: true
  56490. });
  56491. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  56492. get: function () {
  56493. if (this.hand === 'right') {
  56494. return this.onSecondaryButtonStateChangedObservable;
  56495. }
  56496. else {
  56497. throw new Error('No B button on left hand');
  56498. }
  56499. },
  56500. enumerable: true,
  56501. configurable: true
  56502. });
  56503. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  56504. get: function () {
  56505. if (this.hand === 'left') {
  56506. return this.onMainButtonStateChangedObservable;
  56507. }
  56508. else {
  56509. throw new Error('No X button on right hand');
  56510. }
  56511. },
  56512. enumerable: true,
  56513. configurable: true
  56514. });
  56515. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  56516. get: function () {
  56517. if (this.hand === 'left') {
  56518. return this.onSecondaryButtonStateChangedObservable;
  56519. }
  56520. else {
  56521. throw new Error('No Y button on right hand');
  56522. }
  56523. },
  56524. enumerable: true,
  56525. configurable: true
  56526. });
  56527. /*
  56528. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  56529. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  56530. 2) secondary trigger (same)
  56531. 3) A (right) X (left), touch, pressed = value
  56532. 4) B / Y
  56533. 5) thumb rest
  56534. */
  56535. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56536. var notifyObject = state; //{ state: state, changes: changes };
  56537. var triggerDirection = this.hand === 'right' ? -1 : 1;
  56538. switch (buttonIdx) {
  56539. case 0:
  56540. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  56541. return;
  56542. case 1:// index trigger
  56543. if (this._defaultModel) {
  56544. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  56545. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  56546. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  56547. }
  56548. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  56549. return;
  56550. case 2:// secondary trigger
  56551. if (this._defaultModel) {
  56552. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  56553. }
  56554. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  56555. return;
  56556. case 3:
  56557. if (this._defaultModel) {
  56558. if (notifyObject.pressed) {
  56559. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  56560. }
  56561. else {
  56562. (this._defaultModel.getChildren()[1]).position.y = 0;
  56563. }
  56564. }
  56565. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  56566. return;
  56567. case 4:
  56568. if (this._defaultModel) {
  56569. if (notifyObject.pressed) {
  56570. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  56571. }
  56572. else {
  56573. (this._defaultModel.getChildren()[2]).position.y = 0;
  56574. }
  56575. }
  56576. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  56577. return;
  56578. case 5:
  56579. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  56580. return;
  56581. }
  56582. };
  56583. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  56584. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  56585. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  56586. return OculusTouchController;
  56587. }(BABYLON.WebVRController));
  56588. BABYLON.OculusTouchController = OculusTouchController;
  56589. })(BABYLON || (BABYLON = {}));
  56590. //# sourceMappingURL=babylon.oculusTouchController.js.map
  56591. var BABYLON;
  56592. (function (BABYLON) {
  56593. var ViveController = /** @class */ (function (_super) {
  56594. __extends(ViveController, _super);
  56595. function ViveController(vrGamepad) {
  56596. var _this = _super.call(this, vrGamepad) || this;
  56597. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  56598. return _this;
  56599. }
  56600. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  56601. var _this = this;
  56602. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  56603. /*
  56604. Parent Mesh name: ViveWand
  56605. - body
  56606. - r_gripper
  56607. - l_gripper
  56608. - menu_button
  56609. - system_button
  56610. - trackpad
  56611. - trigger
  56612. - LED
  56613. */
  56614. _this._defaultModel = newMeshes[1];
  56615. _this.attachToMesh(_this._defaultModel);
  56616. if (meshLoaded) {
  56617. meshLoaded(_this._defaultModel);
  56618. }
  56619. });
  56620. };
  56621. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  56622. get: function () {
  56623. return this.onMainButtonStateChangedObservable;
  56624. },
  56625. enumerable: true,
  56626. configurable: true
  56627. });
  56628. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  56629. get: function () {
  56630. return this.onMainButtonStateChangedObservable;
  56631. },
  56632. enumerable: true,
  56633. configurable: true
  56634. });
  56635. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  56636. get: function () {
  56637. return this.onSecondaryButtonStateChangedObservable;
  56638. },
  56639. enumerable: true,
  56640. configurable: true
  56641. });
  56642. /**
  56643. * Vive mapping:
  56644. * 0: touchpad
  56645. * 1: trigger
  56646. * 2: left AND right buttons
  56647. * 3: menu button
  56648. */
  56649. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56650. var notifyObject = state; //{ state: state, changes: changes };
  56651. switch (buttonIdx) {
  56652. case 0:
  56653. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  56654. return;
  56655. case 1:// index trigger
  56656. if (this._defaultModel) {
  56657. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  56658. }
  56659. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  56660. return;
  56661. case 2:// left AND right button
  56662. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  56663. return;
  56664. case 3:
  56665. if (this._defaultModel) {
  56666. if (notifyObject.pressed) {
  56667. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  56668. }
  56669. else {
  56670. (this._defaultModel.getChildren()[2]).position.y = 0;
  56671. }
  56672. }
  56673. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  56674. return;
  56675. }
  56676. };
  56677. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  56678. ViveController.MODEL_FILENAME = 'wand.babylon';
  56679. return ViveController;
  56680. }(BABYLON.WebVRController));
  56681. BABYLON.ViveController = ViveController;
  56682. })(BABYLON || (BABYLON = {}));
  56683. //# sourceMappingURL=babylon.viveController.js.map
  56684. var BABYLON;
  56685. (function (BABYLON) {
  56686. var GenericController = /** @class */ (function (_super) {
  56687. __extends(GenericController, _super);
  56688. function GenericController(vrGamepad) {
  56689. return _super.call(this, vrGamepad) || this;
  56690. }
  56691. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  56692. var _this = this;
  56693. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  56694. _this._defaultModel = newMeshes[1];
  56695. _this.attachToMesh(_this._defaultModel);
  56696. if (meshLoaded) {
  56697. meshLoaded(_this._defaultModel);
  56698. }
  56699. });
  56700. };
  56701. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56702. console.log("Button id: " + buttonIdx + "state: ");
  56703. console.dir(state);
  56704. };
  56705. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  56706. GenericController.MODEL_FILENAME = 'generic.babylon';
  56707. return GenericController;
  56708. }(BABYLON.WebVRController));
  56709. BABYLON.GenericController = GenericController;
  56710. })(BABYLON || (BABYLON = {}));
  56711. //# sourceMappingURL=babylon.genericController.js.map
  56712. var BABYLON;
  56713. (function (BABYLON) {
  56714. var LoadedMeshInfo = /** @class */ (function () {
  56715. function LoadedMeshInfo() {
  56716. this.buttonMeshes = {};
  56717. this.axisMeshes = {};
  56718. }
  56719. return LoadedMeshInfo;
  56720. }());
  56721. var WindowsMotionController = /** @class */ (function (_super) {
  56722. __extends(WindowsMotionController, _super);
  56723. function WindowsMotionController(vrGamepad) {
  56724. var _this = _super.call(this, vrGamepad) || this;
  56725. _this._mapping = {
  56726. // Semantic button names
  56727. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  56728. // A mapping of the button name to glTF model node name
  56729. // that should be transformed by button value.
  56730. buttonMeshNames: {
  56731. 'trigger': 'SELECT',
  56732. 'menu': 'MENU',
  56733. 'grip': 'GRASP',
  56734. 'thumbstick': 'THUMBSTICK_PRESS',
  56735. 'trackpad': 'TOUCHPAD_PRESS'
  56736. },
  56737. // This mapping is used to translate from the Motion Controller to Babylon semantics
  56738. buttonObservableNames: {
  56739. 'trigger': 'onTriggerStateChangedObservable',
  56740. 'menu': 'onSecondaryButtonStateChangedObservable',
  56741. 'grip': 'onMainButtonStateChangedObservable',
  56742. 'thumbstick': 'onPadStateChangedObservable',
  56743. 'trackpad': 'onTrackpadChangedObservable'
  56744. },
  56745. // A mapping of the axis name to glTF model node name
  56746. // that should be transformed by axis value.
  56747. // This array mirrors the browserGamepad.axes array, such that
  56748. // the mesh corresponding to axis 0 is in this array index 0.
  56749. axisMeshNames: [
  56750. 'THUMBSTICK_X',
  56751. 'THUMBSTICK_Y',
  56752. 'TOUCHPAD_TOUCH_X',
  56753. 'TOUCHPAD_TOUCH_Y'
  56754. ],
  56755. pointingPoseMeshName: 'POINTING_POSE'
  56756. };
  56757. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  56758. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  56759. _this._loadedMeshInfo = null;
  56760. return _this;
  56761. }
  56762. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  56763. get: function () {
  56764. return this.onTriggerStateChangedObservable;
  56765. },
  56766. enumerable: true,
  56767. configurable: true
  56768. });
  56769. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  56770. get: function () {
  56771. return this.onSecondaryButtonStateChangedObservable;
  56772. },
  56773. enumerable: true,
  56774. configurable: true
  56775. });
  56776. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  56777. get: function () {
  56778. return this.onMainButtonStateChangedObservable;
  56779. },
  56780. enumerable: true,
  56781. configurable: true
  56782. });
  56783. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  56784. get: function () {
  56785. return this.onPadStateChangedObservable;
  56786. },
  56787. enumerable: true,
  56788. configurable: true
  56789. });
  56790. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  56791. get: function () {
  56792. return this.onTrackpadChangedObservable;
  56793. },
  56794. enumerable: true,
  56795. configurable: true
  56796. });
  56797. /**
  56798. * Called once per frame by the engine.
  56799. */
  56800. WindowsMotionController.prototype.update = function () {
  56801. _super.prototype.update.call(this);
  56802. // Only need to animate axes if there is a loaded mesh
  56803. if (this._loadedMeshInfo) {
  56804. if (this.browserGamepad.axes) {
  56805. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  56806. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  56807. }
  56808. }
  56809. }
  56810. };
  56811. /**
  56812. * Called once for each button that changed state since the last frame
  56813. * @param buttonIdx Which button index changed
  56814. * @param state New state of the button
  56815. * @param changes Which properties on the state changed since last frame
  56816. */
  56817. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56818. var buttonName = this._mapping.buttons[buttonIdx];
  56819. if (!buttonName) {
  56820. return;
  56821. }
  56822. // Only emit events for buttons that we know how to map from index to name
  56823. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  56824. if (observable) {
  56825. observable.notifyObservers(state);
  56826. }
  56827. this.lerpButtonTransform(buttonName, state.value);
  56828. };
  56829. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  56830. // If there is no loaded mesh, there is nothing to transform.
  56831. if (!this._loadedMeshInfo) {
  56832. return;
  56833. }
  56834. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  56835. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  56836. return;
  56837. }
  56838. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  56839. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  56840. };
  56841. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  56842. if (!this._loadedMeshInfo) {
  56843. return;
  56844. }
  56845. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  56846. if (!meshInfo) {
  56847. return;
  56848. }
  56849. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  56850. return;
  56851. }
  56852. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  56853. var lerpValue = axisValue * 0.5 + 0.5;
  56854. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  56855. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  56856. };
  56857. /**
  56858. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  56859. * @param scene scene in which to add meshes
  56860. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  56861. */
  56862. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  56863. var _this = this;
  56864. if (forceDefault === void 0) { forceDefault = false; }
  56865. var path;
  56866. var filename;
  56867. // Checking if GLB loader is present
  56868. if (BABYLON.SceneLoader.GetPluginForExtension("glb")) {
  56869. // Determine the device specific folder based on the ID suffix
  56870. var device = 'default';
  56871. if (this.id && !forceDefault) {
  56872. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  56873. device = ((match && match[0]) || device);
  56874. }
  56875. // Hand
  56876. if (this.hand === 'left') {
  56877. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  56878. }
  56879. else {
  56880. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  56881. }
  56882. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  56883. }
  56884. else {
  56885. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  56886. path = BABYLON.GenericController.MODEL_BASE_URL;
  56887. filename = BABYLON.GenericController.MODEL_FILENAME;
  56888. }
  56889. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  56890. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  56891. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  56892. if (!_this._loadedMeshInfo) {
  56893. return;
  56894. }
  56895. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  56896. _this.attachToMesh(_this._defaultModel);
  56897. if (meshLoaded) {
  56898. meshLoaded(_this._defaultModel);
  56899. }
  56900. }, null, function (scene, message) {
  56901. BABYLON.Tools.Log(message);
  56902. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  56903. if (!forceDefault) {
  56904. _this.initControllerMesh(scene, meshLoaded, true);
  56905. }
  56906. });
  56907. };
  56908. /**
  56909. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  56910. * can be transformed by button presses and axes values, based on this._mapping.
  56911. *
  56912. * @param scene scene in which the meshes exist
  56913. * @param meshes list of meshes that make up the controller model to process
  56914. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  56915. */
  56916. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  56917. var loadedMeshInfo = null;
  56918. // Create a new mesh to contain the glTF hierarchy
  56919. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  56920. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  56921. var childMesh = null;
  56922. for (var i = 0; i < meshes.length; i++) {
  56923. var mesh = meshes[i];
  56924. if (!mesh.parent) {
  56925. // Exclude controller meshes from picking results
  56926. mesh.isPickable = false;
  56927. // Handle root node, attach to the new parentMesh
  56928. childMesh = mesh;
  56929. break;
  56930. }
  56931. }
  56932. if (childMesh) {
  56933. childMesh.setParent(parentMesh);
  56934. // Create our mesh info. Note that this method will always return non-null.
  56935. loadedMeshInfo = this.createMeshInfo(parentMesh);
  56936. }
  56937. else {
  56938. BABYLON.Tools.Warn('Could not find root node in model file.');
  56939. }
  56940. return loadedMeshInfo;
  56941. };
  56942. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  56943. var loadedMeshInfo = new LoadedMeshInfo();
  56944. var i;
  56945. loadedMeshInfo.rootNode = rootNode;
  56946. // Reset the caches
  56947. loadedMeshInfo.buttonMeshes = {};
  56948. loadedMeshInfo.axisMeshes = {};
  56949. // Button Meshes
  56950. for (i = 0; i < this._mapping.buttons.length; i++) {
  56951. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  56952. if (!buttonMeshName) {
  56953. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  56954. continue;
  56955. }
  56956. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  56957. if (!buttonMesh) {
  56958. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  56959. continue;
  56960. }
  56961. var buttonMeshInfo = {
  56962. index: i,
  56963. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  56964. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  56965. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  56966. };
  56967. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  56968. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  56969. }
  56970. else {
  56971. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  56972. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  56973. '(VALUE: ' + !!buttonMeshInfo.value +
  56974. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  56975. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  56976. ')');
  56977. }
  56978. }
  56979. // Axis Meshes
  56980. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  56981. var axisMeshName = this._mapping.axisMeshNames[i];
  56982. if (!axisMeshName) {
  56983. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  56984. continue;
  56985. }
  56986. var axisMesh = getChildByName(rootNode, axisMeshName);
  56987. if (!axisMesh) {
  56988. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  56989. continue;
  56990. }
  56991. var axisMeshInfo = {
  56992. index: i,
  56993. value: getImmediateChildByName(axisMesh, 'VALUE'),
  56994. min: getImmediateChildByName(axisMesh, 'MIN'),
  56995. max: getImmediateChildByName(axisMesh, 'MAX')
  56996. };
  56997. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  56998. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  56999. }
  57000. else {
  57001. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  57002. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  57003. '(VALUE: ' + !!axisMeshInfo.value +
  57004. ', MIN: ' + !!axisMeshInfo.min +
  57005. ', MAX:' + !!axisMeshInfo.max +
  57006. ')');
  57007. }
  57008. }
  57009. // Pointing Ray
  57010. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  57011. if (!loadedMeshInfo.pointingPoseNode) {
  57012. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  57013. }
  57014. return loadedMeshInfo;
  57015. // Look through all children recursively. This will return null if no mesh exists with the given name.
  57016. function getChildByName(node, name) {
  57017. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  57018. }
  57019. // Look through only immediate children. This will return null if no mesh exists with the given name.
  57020. function getImmediateChildByName(node, name) {
  57021. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  57022. }
  57023. };
  57024. WindowsMotionController.prototype.getForwardRay = function (length) {
  57025. if (length === void 0) { length = 100; }
  57026. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  57027. return _super.prototype.getForwardRay.call(this, length);
  57028. }
  57029. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  57030. var origin = m.getTranslation();
  57031. var forward = new BABYLON.Vector3(0, 0, -1);
  57032. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  57033. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  57034. return new BABYLON.Ray(origin, direction, length);
  57035. };
  57036. WindowsMotionController.prototype.dispose = function () {
  57037. _super.prototype.dispose.call(this);
  57038. this.onTrackpadChangedObservable.clear();
  57039. };
  57040. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  57041. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  57042. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  57043. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  57044. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  57045. return WindowsMotionController;
  57046. }(BABYLON.WebVRController));
  57047. BABYLON.WindowsMotionController = WindowsMotionController;
  57048. })(BABYLON || (BABYLON = {}));
  57049. //# sourceMappingURL=babylon.windowsMotionController.js.map
  57050. var BABYLON;
  57051. (function (BABYLON) {
  57052. var FollowCamera = /** @class */ (function (_super) {
  57053. __extends(FollowCamera, _super);
  57054. function FollowCamera(name, position, scene, lockedTarget) {
  57055. if (lockedTarget === void 0) { lockedTarget = null; }
  57056. var _this = _super.call(this, name, position, scene) || this;
  57057. _this.radius = 12;
  57058. _this.rotationOffset = 0;
  57059. _this.heightOffset = 4;
  57060. _this.cameraAcceleration = 0.05;
  57061. _this.maxCameraSpeed = 20;
  57062. _this.lockedTarget = lockedTarget;
  57063. return _this;
  57064. }
  57065. FollowCamera.prototype.getRadians = function (degrees) {
  57066. return degrees * Math.PI / 180;
  57067. };
  57068. FollowCamera.prototype.follow = function (cameraTarget) {
  57069. if (!cameraTarget)
  57070. return;
  57071. var yRotation;
  57072. if (cameraTarget.rotationQuaternion) {
  57073. var rotMatrix = new BABYLON.Matrix();
  57074. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  57075. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  57076. }
  57077. else {
  57078. yRotation = cameraTarget.rotation.y;
  57079. }
  57080. var radians = this.getRadians(this.rotationOffset) + yRotation;
  57081. var targetPosition = cameraTarget.getAbsolutePosition();
  57082. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  57083. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  57084. var dx = targetX - this.position.x;
  57085. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  57086. var dz = (targetZ) - this.position.z;
  57087. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  57088. var vy = dy * this.cameraAcceleration;
  57089. var vz = dz * this.cameraAcceleration * 2;
  57090. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  57091. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  57092. }
  57093. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  57094. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  57095. }
  57096. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  57097. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  57098. }
  57099. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  57100. this.setTarget(targetPosition);
  57101. };
  57102. FollowCamera.prototype._checkInputs = function () {
  57103. _super.prototype._checkInputs.call(this);
  57104. if (this.lockedTarget) {
  57105. this.follow(this.lockedTarget);
  57106. }
  57107. };
  57108. FollowCamera.prototype.getClassName = function () {
  57109. return "FollowCamera";
  57110. };
  57111. __decorate([
  57112. BABYLON.serialize()
  57113. ], FollowCamera.prototype, "radius", void 0);
  57114. __decorate([
  57115. BABYLON.serialize()
  57116. ], FollowCamera.prototype, "rotationOffset", void 0);
  57117. __decorate([
  57118. BABYLON.serialize()
  57119. ], FollowCamera.prototype, "heightOffset", void 0);
  57120. __decorate([
  57121. BABYLON.serialize()
  57122. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  57123. __decorate([
  57124. BABYLON.serialize()
  57125. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  57126. __decorate([
  57127. BABYLON.serializeAsMeshReference("lockedTargetId")
  57128. ], FollowCamera.prototype, "lockedTarget", void 0);
  57129. return FollowCamera;
  57130. }(BABYLON.TargetCamera));
  57131. BABYLON.FollowCamera = FollowCamera;
  57132. var ArcFollowCamera = /** @class */ (function (_super) {
  57133. __extends(ArcFollowCamera, _super);
  57134. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  57135. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  57136. _this.alpha = alpha;
  57137. _this.beta = beta;
  57138. _this.radius = radius;
  57139. _this.target = target;
  57140. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  57141. _this.follow();
  57142. return _this;
  57143. }
  57144. ArcFollowCamera.prototype.follow = function () {
  57145. if (!this.target) {
  57146. return;
  57147. }
  57148. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  57149. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  57150. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  57151. var targetPosition = this.target.getAbsolutePosition();
  57152. this.position = targetPosition.add(this._cartesianCoordinates);
  57153. this.setTarget(targetPosition);
  57154. };
  57155. ArcFollowCamera.prototype._checkInputs = function () {
  57156. _super.prototype._checkInputs.call(this);
  57157. this.follow();
  57158. };
  57159. ArcFollowCamera.prototype.getClassName = function () {
  57160. return "ArcFollowCamera";
  57161. };
  57162. return ArcFollowCamera;
  57163. }(BABYLON.TargetCamera));
  57164. BABYLON.ArcFollowCamera = ArcFollowCamera;
  57165. })(BABYLON || (BABYLON = {}));
  57166. //# sourceMappingURL=babylon.followCamera.js.map
  57167. var BABYLON;
  57168. (function (BABYLON) {
  57169. // We're mainly based on the logic defined into the FreeCamera code
  57170. var UniversalCamera = /** @class */ (function (_super) {
  57171. __extends(UniversalCamera, _super);
  57172. //-- end properties for backward compatibility for inputs
  57173. function UniversalCamera(name, position, scene) {
  57174. var _this = _super.call(this, name, position, scene) || this;
  57175. _this.inputs.addGamepad();
  57176. return _this;
  57177. }
  57178. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  57179. //-- Begin properties for backward compatibility for inputs
  57180. get: function () {
  57181. var gamepad = this.inputs.attached["gamepad"];
  57182. if (gamepad)
  57183. return gamepad.gamepadAngularSensibility;
  57184. return 0;
  57185. },
  57186. set: function (value) {
  57187. var gamepad = this.inputs.attached["gamepad"];
  57188. if (gamepad)
  57189. gamepad.gamepadAngularSensibility = value;
  57190. },
  57191. enumerable: true,
  57192. configurable: true
  57193. });
  57194. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  57195. get: function () {
  57196. var gamepad = this.inputs.attached["gamepad"];
  57197. if (gamepad)
  57198. return gamepad.gamepadMoveSensibility;
  57199. return 0;
  57200. },
  57201. set: function (value) {
  57202. var gamepad = this.inputs.attached["gamepad"];
  57203. if (gamepad)
  57204. gamepad.gamepadMoveSensibility = value;
  57205. },
  57206. enumerable: true,
  57207. configurable: true
  57208. });
  57209. UniversalCamera.prototype.getClassName = function () {
  57210. return "UniversalCamera";
  57211. };
  57212. return UniversalCamera;
  57213. }(BABYLON.TouchCamera));
  57214. BABYLON.UniversalCamera = UniversalCamera;
  57215. })(BABYLON || (BABYLON = {}));
  57216. //# sourceMappingURL=babylon.universalCamera.js.map
  57217. var BABYLON;
  57218. (function (BABYLON) {
  57219. // We're mainly based on the logic defined into the FreeCamera code
  57220. var GamepadCamera = /** @class */ (function (_super) {
  57221. __extends(GamepadCamera, _super);
  57222. //-- end properties for backward compatibility for inputs
  57223. function GamepadCamera(name, position, scene) {
  57224. return _super.call(this, name, position, scene) || this;
  57225. }
  57226. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  57227. //-- Begin properties for backward compatibility for inputs
  57228. get: function () {
  57229. var gamepad = this.inputs.attached["gamepad"];
  57230. if (gamepad)
  57231. return gamepad.gamepadAngularSensibility;
  57232. return 0;
  57233. },
  57234. set: function (value) {
  57235. var gamepad = this.inputs.attached["gamepad"];
  57236. if (gamepad)
  57237. gamepad.gamepadAngularSensibility = value;
  57238. },
  57239. enumerable: true,
  57240. configurable: true
  57241. });
  57242. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  57243. get: function () {
  57244. var gamepad = this.inputs.attached["gamepad"];
  57245. if (gamepad)
  57246. return gamepad.gamepadMoveSensibility;
  57247. return 0;
  57248. },
  57249. set: function (value) {
  57250. var gamepad = this.inputs.attached["gamepad"];
  57251. if (gamepad)
  57252. gamepad.gamepadMoveSensibility = value;
  57253. },
  57254. enumerable: true,
  57255. configurable: true
  57256. });
  57257. GamepadCamera.prototype.getClassName = function () {
  57258. return "GamepadCamera";
  57259. };
  57260. return GamepadCamera;
  57261. }(BABYLON.UniversalCamera));
  57262. BABYLON.GamepadCamera = GamepadCamera;
  57263. })(BABYLON || (BABYLON = {}));
  57264. //# sourceMappingURL=babylon.gamepadCamera.js.map
  57265. var BABYLON;
  57266. (function (BABYLON) {
  57267. var PostProcessRenderPipelineManager = /** @class */ (function () {
  57268. function PostProcessRenderPipelineManager() {
  57269. this._renderPipelines = {};
  57270. }
  57271. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  57272. this._renderPipelines[renderPipeline._name] = renderPipeline;
  57273. };
  57274. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  57275. if (unique === void 0) { unique = false; }
  57276. var renderPipeline = this._renderPipelines[renderPipelineName];
  57277. if (!renderPipeline) {
  57278. return;
  57279. }
  57280. renderPipeline._attachCameras(cameras, unique);
  57281. };
  57282. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  57283. var renderPipeline = this._renderPipelines[renderPipelineName];
  57284. if (!renderPipeline) {
  57285. return;
  57286. }
  57287. renderPipeline._detachCameras(cameras);
  57288. };
  57289. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  57290. var renderPipeline = this._renderPipelines[renderPipelineName];
  57291. if (!renderPipeline) {
  57292. return;
  57293. }
  57294. renderPipeline._enableEffect(renderEffectName, cameras);
  57295. };
  57296. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  57297. var renderPipeline = this._renderPipelines[renderPipelineName];
  57298. if (!renderPipeline) {
  57299. return;
  57300. }
  57301. renderPipeline._disableEffect(renderEffectName, cameras);
  57302. };
  57303. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  57304. var renderPipeline = this._renderPipelines[renderPipelineName];
  57305. if (!renderPipeline) {
  57306. return;
  57307. }
  57308. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  57309. };
  57310. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  57311. var renderPipeline = this._renderPipelines[renderPipelineName];
  57312. if (!renderPipeline) {
  57313. return;
  57314. }
  57315. renderPipeline._disableDisplayOnlyPass(cameras);
  57316. };
  57317. PostProcessRenderPipelineManager.prototype.update = function () {
  57318. for (var renderPipelineName in this._renderPipelines) {
  57319. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  57320. var pipeline = this._renderPipelines[renderPipelineName];
  57321. if (!pipeline.isSupported) {
  57322. pipeline.dispose();
  57323. delete this._renderPipelines[renderPipelineName];
  57324. }
  57325. else {
  57326. pipeline._update();
  57327. }
  57328. }
  57329. }
  57330. };
  57331. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  57332. for (var renderPipelineName in this._renderPipelines) {
  57333. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  57334. var pipeline = this._renderPipelines[renderPipelineName];
  57335. pipeline._rebuild();
  57336. }
  57337. }
  57338. };
  57339. PostProcessRenderPipelineManager.prototype.dispose = function () {
  57340. for (var renderPipelineName in this._renderPipelines) {
  57341. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  57342. var pipeline = this._renderPipelines[renderPipelineName];
  57343. pipeline.dispose();
  57344. }
  57345. }
  57346. };
  57347. return PostProcessRenderPipelineManager;
  57348. }());
  57349. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  57350. })(BABYLON || (BABYLON = {}));
  57351. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  57352. var BABYLON;
  57353. (function (BABYLON) {
  57354. var PostProcessRenderPass = /** @class */ (function () {
  57355. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  57356. this._refCount = 0;
  57357. this._name = name;
  57358. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  57359. this.setRenderList(renderList);
  57360. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  57361. this._renderTexture.onAfterRenderObservable.add(afterRender);
  57362. this._scene = scene;
  57363. this._renderList = renderList;
  57364. }
  57365. // private
  57366. PostProcessRenderPass.prototype._incRefCount = function () {
  57367. if (this._refCount === 0) {
  57368. this._scene.customRenderTargets.push(this._renderTexture);
  57369. }
  57370. return ++this._refCount;
  57371. };
  57372. PostProcessRenderPass.prototype._decRefCount = function () {
  57373. this._refCount--;
  57374. if (this._refCount <= 0) {
  57375. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  57376. }
  57377. return this._refCount;
  57378. };
  57379. PostProcessRenderPass.prototype._update = function () {
  57380. this.setRenderList(this._renderList);
  57381. };
  57382. // public
  57383. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  57384. this._renderTexture.renderList = renderList;
  57385. };
  57386. PostProcessRenderPass.prototype.getRenderTexture = function () {
  57387. return this._renderTexture;
  57388. };
  57389. return PostProcessRenderPass;
  57390. }());
  57391. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  57392. })(BABYLON || (BABYLON = {}));
  57393. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  57394. var BABYLON;
  57395. (function (BABYLON) {
  57396. var PostProcessRenderEffect = /** @class */ (function () {
  57397. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  57398. this._name = name;
  57399. this._singleInstance = singleInstance || true;
  57400. this._getPostProcess = getPostProcess;
  57401. this._cameras = {};
  57402. this._indicesForCamera = {};
  57403. this._postProcesses = {};
  57404. this._renderPasses = {};
  57405. this._renderEffectAsPasses = {};
  57406. }
  57407. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  57408. get: function () {
  57409. for (var index in this._postProcesses) {
  57410. if (!this._postProcesses[index].isSupported) {
  57411. return false;
  57412. }
  57413. }
  57414. return true;
  57415. },
  57416. enumerable: true,
  57417. configurable: true
  57418. });
  57419. PostProcessRenderEffect.prototype._update = function () {
  57420. for (var renderPassName in this._renderPasses) {
  57421. this._renderPasses[renderPassName]._update();
  57422. }
  57423. };
  57424. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  57425. this._renderPasses[renderPass._name] = renderPass;
  57426. this._linkParameters();
  57427. };
  57428. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  57429. delete this._renderPasses[renderPass._name];
  57430. this._linkParameters();
  57431. };
  57432. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  57433. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  57434. this._linkParameters();
  57435. };
  57436. PostProcessRenderEffect.prototype.getPass = function (passName) {
  57437. for (var renderPassName in this._renderPasses) {
  57438. if (renderPassName === passName) {
  57439. return this._renderPasses[passName];
  57440. }
  57441. }
  57442. return null;
  57443. };
  57444. PostProcessRenderEffect.prototype.emptyPasses = function () {
  57445. this._renderPasses = {};
  57446. this._linkParameters();
  57447. };
  57448. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  57449. var cameraKey;
  57450. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57451. if (!cams) {
  57452. return;
  57453. }
  57454. for (var i = 0; i < cams.length; i++) {
  57455. var camera = cams[i];
  57456. var cameraName = camera.name;
  57457. if (this._singleInstance) {
  57458. cameraKey = 0;
  57459. }
  57460. else {
  57461. cameraKey = cameraName;
  57462. }
  57463. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  57464. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  57465. if (!this._indicesForCamera[cameraName]) {
  57466. this._indicesForCamera[cameraName] = [];
  57467. }
  57468. this._indicesForCamera[cameraName].push(index);
  57469. if (!this._cameras[cameraName]) {
  57470. this._cameras[cameraName] = camera;
  57471. }
  57472. for (var passName in this._renderPasses) {
  57473. this._renderPasses[passName]._incRefCount();
  57474. }
  57475. }
  57476. this._linkParameters();
  57477. };
  57478. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  57479. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57480. if (!cams) {
  57481. return;
  57482. }
  57483. for (var i = 0; i < cams.length; i++) {
  57484. var camera = cams[i];
  57485. var cameraName = camera.name;
  57486. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  57487. if (this._cameras[cameraName]) {
  57488. //this._indicesForCamera.splice(index, 1);
  57489. this._cameras[cameraName] = null;
  57490. }
  57491. for (var passName in this._renderPasses) {
  57492. this._renderPasses[passName]._decRefCount();
  57493. }
  57494. }
  57495. };
  57496. PostProcessRenderEffect.prototype._enable = function (cameras) {
  57497. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57498. if (!cams) {
  57499. return;
  57500. }
  57501. for (var i = 0; i < cams.length; i++) {
  57502. var camera = cams[i];
  57503. var cameraName = camera.name;
  57504. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  57505. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  57506. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  57507. }
  57508. }
  57509. for (var passName in this._renderPasses) {
  57510. this._renderPasses[passName]._incRefCount();
  57511. }
  57512. }
  57513. };
  57514. PostProcessRenderEffect.prototype._disable = function (cameras) {
  57515. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57516. if (!cams) {
  57517. return;
  57518. }
  57519. for (var i = 0; i < cams.length; i++) {
  57520. var camera = cams[i];
  57521. var cameraName = camera.Name;
  57522. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  57523. for (var passName in this._renderPasses) {
  57524. this._renderPasses[passName]._decRefCount();
  57525. }
  57526. }
  57527. };
  57528. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  57529. if (this._singleInstance) {
  57530. return this._postProcesses[0];
  57531. }
  57532. else {
  57533. if (!camera) {
  57534. return null;
  57535. }
  57536. return this._postProcesses[camera.name];
  57537. }
  57538. };
  57539. PostProcessRenderEffect.prototype._linkParameters = function () {
  57540. var _this = this;
  57541. for (var index in this._postProcesses) {
  57542. if (this.applyParameters) {
  57543. this.applyParameters(this._postProcesses[index]);
  57544. }
  57545. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  57546. _this._linkTextures(effect);
  57547. });
  57548. }
  57549. };
  57550. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  57551. for (var renderPassName in this._renderPasses) {
  57552. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  57553. }
  57554. for (var renderEffectName in this._renderEffectAsPasses) {
  57555. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  57556. }
  57557. };
  57558. return PostProcessRenderEffect;
  57559. }());
  57560. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  57561. })(BABYLON || (BABYLON = {}));
  57562. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  57563. var BABYLON;
  57564. (function (BABYLON) {
  57565. var PostProcessRenderPipeline = /** @class */ (function () {
  57566. function PostProcessRenderPipeline(engine, name) {
  57567. this._engine = engine;
  57568. this._name = name;
  57569. this._renderEffects = {};
  57570. this._renderEffectsForIsolatedPass = new Array();
  57571. this._cameras = [];
  57572. }
  57573. PostProcessRenderPipeline.prototype.getClassName = function () {
  57574. return "PostProcessRenderPipeline";
  57575. };
  57576. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  57577. get: function () {
  57578. for (var renderEffectName in this._renderEffects) {
  57579. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57580. if (!this._renderEffects[renderEffectName].isSupported) {
  57581. return false;
  57582. }
  57583. }
  57584. }
  57585. return true;
  57586. },
  57587. enumerable: true,
  57588. configurable: true
  57589. });
  57590. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  57591. this._renderEffects[renderEffect._name] = renderEffect;
  57592. };
  57593. // private
  57594. PostProcessRenderPipeline.prototype._rebuild = function () {
  57595. };
  57596. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  57597. var renderEffects = this._renderEffects[renderEffectName];
  57598. if (!renderEffects) {
  57599. return;
  57600. }
  57601. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  57602. };
  57603. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  57604. var renderEffects = this._renderEffects[renderEffectName];
  57605. if (!renderEffects) {
  57606. return;
  57607. }
  57608. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  57609. };
  57610. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  57611. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57612. if (!cams) {
  57613. return;
  57614. }
  57615. var indicesToDelete = [];
  57616. var i;
  57617. for (i = 0; i < cams.length; i++) {
  57618. var camera = cams[i];
  57619. var cameraName = camera.name;
  57620. if (this._cameras.indexOf(camera) === -1) {
  57621. this._cameras[cameraName] = camera;
  57622. }
  57623. else if (unique) {
  57624. indicesToDelete.push(i);
  57625. }
  57626. }
  57627. for (i = 0; i < indicesToDelete.length; i++) {
  57628. cameras.splice(indicesToDelete[i], 1);
  57629. }
  57630. for (var renderEffectName in this._renderEffects) {
  57631. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57632. this._renderEffects[renderEffectName]._attachCameras(cams);
  57633. }
  57634. }
  57635. };
  57636. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  57637. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57638. if (!cams) {
  57639. return;
  57640. }
  57641. for (var renderEffectName in this._renderEffects) {
  57642. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57643. this._renderEffects[renderEffectName]._detachCameras(cams);
  57644. }
  57645. }
  57646. for (var i = 0; i < cams.length; i++) {
  57647. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  57648. }
  57649. };
  57650. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  57651. var _this = this;
  57652. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57653. if (!cams) {
  57654. return;
  57655. }
  57656. var pass = null;
  57657. var renderEffectName;
  57658. for (renderEffectName in this._renderEffects) {
  57659. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57660. pass = this._renderEffects[renderEffectName].getPass(passName);
  57661. if (pass != null) {
  57662. break;
  57663. }
  57664. }
  57665. }
  57666. if (pass === null) {
  57667. return;
  57668. }
  57669. for (renderEffectName in this._renderEffects) {
  57670. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57671. this._renderEffects[renderEffectName]._disable(cams);
  57672. }
  57673. }
  57674. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  57675. for (var i = 0; i < cams.length; i++) {
  57676. var camera = cams[i];
  57677. var cameraName = camera.name;
  57678. 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); });
  57679. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  57680. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  57681. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  57682. }
  57683. };
  57684. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  57685. var _this = this;
  57686. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57687. if (!cams) {
  57688. return;
  57689. }
  57690. for (var i = 0; i < cams.length; i++) {
  57691. var camera = cams[i];
  57692. var cameraName = camera.name;
  57693. 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); });
  57694. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  57695. }
  57696. for (var renderEffectName in this._renderEffects) {
  57697. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57698. this._renderEffects[renderEffectName]._enable(cams);
  57699. }
  57700. }
  57701. };
  57702. PostProcessRenderPipeline.prototype._update = function () {
  57703. for (var renderEffectName in this._renderEffects) {
  57704. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57705. this._renderEffects[renderEffectName]._update();
  57706. }
  57707. }
  57708. for (var i = 0; i < this._cameras.length; i++) {
  57709. var cameraName = this._cameras[i].name;
  57710. if (this._renderEffectsForIsolatedPass[cameraName]) {
  57711. this._renderEffectsForIsolatedPass[cameraName]._update();
  57712. }
  57713. }
  57714. };
  57715. PostProcessRenderPipeline.prototype._reset = function () {
  57716. this._renderEffects = {};
  57717. this._renderEffectsForIsolatedPass = new Array();
  57718. };
  57719. PostProcessRenderPipeline.prototype.dispose = function () {
  57720. // Must be implemented by children
  57721. };
  57722. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  57723. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  57724. __decorate([
  57725. BABYLON.serialize()
  57726. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  57727. return PostProcessRenderPipeline;
  57728. }());
  57729. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  57730. })(BABYLON || (BABYLON = {}));
  57731. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  57732. var BABYLON;
  57733. (function (BABYLON) {
  57734. var DepthRenderer = /** @class */ (function () {
  57735. function DepthRenderer(scene, type) {
  57736. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  57737. var _this = this;
  57738. this._scene = scene;
  57739. var engine = scene.getEngine();
  57740. // Render target
  57741. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  57742. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57743. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57744. this._depthMap.refreshRate = 1;
  57745. this._depthMap.renderParticles = false;
  57746. this._depthMap.renderList = null;
  57747. // set default depth value to 1.0 (far away)
  57748. this._depthMap.onClearObservable.add(function (engine) {
  57749. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  57750. });
  57751. // Custom render function
  57752. var renderSubMesh = function (subMesh) {
  57753. var mesh = subMesh.getRenderingMesh();
  57754. var scene = _this._scene;
  57755. var engine = scene.getEngine();
  57756. var material = subMesh.getMaterial();
  57757. if (!material) {
  57758. return;
  57759. }
  57760. // Culling and reverse (right handed system)
  57761. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  57762. // Managing instances
  57763. var batch = mesh._getInstancesRenderList(subMesh._id);
  57764. if (batch.mustReturn) {
  57765. return;
  57766. }
  57767. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  57768. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  57769. engine.enableEffect(_this._effect);
  57770. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  57771. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  57772. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  57773. // Alpha test
  57774. if (material && material.needAlphaTesting()) {
  57775. var alphaTexture = material.getAlphaTestTexture();
  57776. if (alphaTexture) {
  57777. _this._effect.setTexture("diffuseSampler", alphaTexture);
  57778. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  57779. }
  57780. }
  57781. // Bones
  57782. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  57783. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  57784. }
  57785. // Draw
  57786. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  57787. }
  57788. };
  57789. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  57790. var index;
  57791. if (depthOnlySubMeshes.length) {
  57792. engine.setColorWrite(false);
  57793. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  57794. renderSubMesh(depthOnlySubMeshes.data[index]);
  57795. }
  57796. engine.setColorWrite(true);
  57797. }
  57798. for (index = 0; index < opaqueSubMeshes.length; index++) {
  57799. renderSubMesh(opaqueSubMeshes.data[index]);
  57800. }
  57801. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  57802. renderSubMesh(alphaTestSubMeshes.data[index]);
  57803. }
  57804. };
  57805. }
  57806. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  57807. var material = subMesh.getMaterial();
  57808. if (material.disableDepthWrite) {
  57809. return false;
  57810. }
  57811. var defines = [];
  57812. var attribs = [BABYLON.VertexBuffer.PositionKind];
  57813. var mesh = subMesh.getMesh();
  57814. // Alpha test
  57815. if (material && material.needAlphaTesting()) {
  57816. defines.push("#define ALPHATEST");
  57817. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  57818. attribs.push(BABYLON.VertexBuffer.UVKind);
  57819. defines.push("#define UV1");
  57820. }
  57821. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  57822. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  57823. defines.push("#define UV2");
  57824. }
  57825. }
  57826. // Bones
  57827. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  57828. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  57829. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  57830. if (mesh.numBoneInfluencers > 4) {
  57831. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  57832. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  57833. }
  57834. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  57835. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  57836. }
  57837. else {
  57838. defines.push("#define NUM_BONE_INFLUENCERS 0");
  57839. }
  57840. // Instances
  57841. if (useInstances) {
  57842. defines.push("#define INSTANCES");
  57843. attribs.push("world0");
  57844. attribs.push("world1");
  57845. attribs.push("world2");
  57846. attribs.push("world3");
  57847. }
  57848. // Get correct effect
  57849. var join = defines.join("\n");
  57850. if (this._cachedDefines !== join) {
  57851. this._cachedDefines = join;
  57852. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  57853. }
  57854. return this._effect.isReady();
  57855. };
  57856. DepthRenderer.prototype.getDepthMap = function () {
  57857. return this._depthMap;
  57858. };
  57859. // Methods
  57860. DepthRenderer.prototype.dispose = function () {
  57861. this._depthMap.dispose();
  57862. };
  57863. return DepthRenderer;
  57864. }());
  57865. BABYLON.DepthRenderer = DepthRenderer;
  57866. })(BABYLON || (BABYLON = {}));
  57867. //# sourceMappingURL=babylon.depthRenderer.js.map
  57868. var BABYLON;
  57869. (function (BABYLON) {
  57870. var SSAORenderingPipeline = /** @class */ (function (_super) {
  57871. __extends(SSAORenderingPipeline, _super);
  57872. /**
  57873. * @constructor
  57874. * @param {string} name - The rendering pipeline name
  57875. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57876. * @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 }
  57877. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57878. */
  57879. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  57880. var _this = _super.call(this, scene.getEngine(), name) || this;
  57881. // Members
  57882. /**
  57883. * The PassPostProcess id in the pipeline that contains the original scene color
  57884. * @type {string}
  57885. */
  57886. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  57887. /**
  57888. * The SSAO PostProcess id in the pipeline
  57889. * @type {string}
  57890. */
  57891. _this.SSAORenderEffect = "SSAORenderEffect";
  57892. /**
  57893. * The horizontal blur PostProcess id in the pipeline
  57894. * @type {string}
  57895. */
  57896. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  57897. /**
  57898. * The vertical blur PostProcess id in the pipeline
  57899. * @type {string}
  57900. */
  57901. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  57902. /**
  57903. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  57904. * @type {string}
  57905. */
  57906. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  57907. /**
  57908. * The output strength of the SSAO post-process. Default value is 1.0.
  57909. * @type {number}
  57910. */
  57911. _this.totalStrength = 1.0;
  57912. /**
  57913. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  57914. * @type {number}
  57915. */
  57916. _this.radius = 0.0001;
  57917. /**
  57918. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  57919. * Must not be equal to fallOff and superior to fallOff.
  57920. * Default value is 0.975
  57921. * @type {number}
  57922. */
  57923. _this.area = 0.0075;
  57924. /**
  57925. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  57926. * Must not be equal to area and inferior to area.
  57927. * Default value is 0.0
  57928. * @type {number}
  57929. */
  57930. _this.fallOff = 0.000001;
  57931. /**
  57932. * The base color of the SSAO post-process
  57933. * The final result is "base + ssao" between [0, 1]
  57934. * @type {number}
  57935. */
  57936. _this.base = 0.5;
  57937. _this._firstUpdate = true;
  57938. _this._scene = scene;
  57939. // Set up assets
  57940. _this._createRandomTexture();
  57941. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  57942. var ssaoRatio = ratio.ssaoRatio || ratio;
  57943. var combineRatio = ratio.combineRatio || ratio;
  57944. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  57945. _this._createSSAOPostProcess(ssaoRatio);
  57946. _this._createBlurPostProcess(ssaoRatio);
  57947. _this._createSSAOCombinePostProcess(combineRatio);
  57948. // Set up pipeline
  57949. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  57950. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  57951. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  57952. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  57953. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  57954. // Finish
  57955. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57956. if (cameras)
  57957. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57958. return _this;
  57959. }
  57960. // Public Methods
  57961. /**
  57962. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  57963. */
  57964. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  57965. if (disableDepthRender === void 0) { disableDepthRender = false; }
  57966. for (var i = 0; i < this._scene.cameras.length; i++) {
  57967. var camera = this._scene.cameras[i];
  57968. this._originalColorPostProcess.dispose(camera);
  57969. this._ssaoPostProcess.dispose(camera);
  57970. this._blurHPostProcess.dispose(camera);
  57971. this._blurVPostProcess.dispose(camera);
  57972. this._ssaoCombinePostProcess.dispose(camera);
  57973. }
  57974. this._randomTexture.dispose();
  57975. if (disableDepthRender)
  57976. this._scene.disableDepthRenderer();
  57977. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57978. _super.prototype.dispose.call(this);
  57979. };
  57980. // Private Methods
  57981. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  57982. var _this = this;
  57983. var size = 16;
  57984. 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);
  57985. 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);
  57986. this._blurHPostProcess.onActivateObservable.add(function () {
  57987. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  57988. _this._blurHPostProcess.kernel = size * dw;
  57989. });
  57990. this._blurVPostProcess.onActivateObservable.add(function () {
  57991. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  57992. _this._blurVPostProcess.kernel = size * dw;
  57993. });
  57994. };
  57995. SSAORenderingPipeline.prototype._rebuild = function () {
  57996. this._firstUpdate = true;
  57997. _super.prototype._rebuild.call(this);
  57998. };
  57999. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  58000. var _this = this;
  58001. var numSamples = 16;
  58002. var sampleSphere = [
  58003. 0.5381, 0.1856, -0.4319,
  58004. 0.1379, 0.2486, 0.4430,
  58005. 0.3371, 0.5679, -0.0057,
  58006. -0.6999, -0.0451, -0.0019,
  58007. 0.0689, -0.1598, -0.8547,
  58008. 0.0560, 0.0069, -0.1843,
  58009. -0.0146, 0.1402, 0.0762,
  58010. 0.0100, -0.1924, -0.0344,
  58011. -0.3577, -0.5301, -0.4358,
  58012. -0.3169, 0.1063, 0.0158,
  58013. 0.0103, -0.5869, 0.0046,
  58014. -0.0897, -0.4940, 0.3287,
  58015. 0.7119, -0.0154, -0.0918,
  58016. -0.0533, 0.0596, -0.5411,
  58017. 0.0352, -0.0631, 0.5460,
  58018. -0.4776, 0.2847, -0.0271
  58019. ];
  58020. var samplesFactor = 1.0 / numSamples;
  58021. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  58022. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  58023. "area", "fallOff", "base", "range", "viewport"
  58024. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  58025. this._ssaoPostProcess.onApply = function (effect) {
  58026. if (_this._firstUpdate) {
  58027. effect.setArray3("sampleSphere", sampleSphere);
  58028. effect.setFloat("samplesFactor", samplesFactor);
  58029. effect.setFloat("randTextureTiles", 4.0);
  58030. }
  58031. effect.setFloat("totalStrength", _this.totalStrength);
  58032. effect.setFloat("radius", _this.radius);
  58033. effect.setFloat("area", _this.area);
  58034. effect.setFloat("fallOff", _this.fallOff);
  58035. effect.setFloat("base", _this.base);
  58036. effect.setTexture("textureSampler", _this._depthTexture);
  58037. effect.setTexture("randomSampler", _this._randomTexture);
  58038. };
  58039. };
  58040. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  58041. var _this = this;
  58042. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58043. this._ssaoCombinePostProcess.onApply = function (effect) {
  58044. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  58045. };
  58046. };
  58047. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  58048. var size = 512;
  58049. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  58050. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58051. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58052. var context = this._randomTexture.getContext();
  58053. var rand = function (min, max) {
  58054. return Math.random() * (max - min) + min;
  58055. };
  58056. var randVector = BABYLON.Vector3.Zero();
  58057. for (var x = 0; x < size; x++) {
  58058. for (var y = 0; y < size; y++) {
  58059. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  58060. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  58061. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  58062. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  58063. context.fillRect(x, y, 1, 1);
  58064. }
  58065. }
  58066. this._randomTexture.update(false);
  58067. };
  58068. __decorate([
  58069. BABYLON.serialize()
  58070. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  58071. __decorate([
  58072. BABYLON.serialize()
  58073. ], SSAORenderingPipeline.prototype, "radius", void 0);
  58074. __decorate([
  58075. BABYLON.serialize()
  58076. ], SSAORenderingPipeline.prototype, "area", void 0);
  58077. __decorate([
  58078. BABYLON.serialize()
  58079. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  58080. __decorate([
  58081. BABYLON.serialize()
  58082. ], SSAORenderingPipeline.prototype, "base", void 0);
  58083. return SSAORenderingPipeline;
  58084. }(BABYLON.PostProcessRenderPipeline));
  58085. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  58086. })(BABYLON || (BABYLON = {}));
  58087. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  58088. var BABYLON;
  58089. (function (BABYLON) {
  58090. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  58091. __extends(SSAO2RenderingPipeline, _super);
  58092. /**
  58093. * @constructor
  58094. * @param {string} name - The rendering pipeline name
  58095. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58096. * @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 }
  58097. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58098. */
  58099. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  58100. var _this = _super.call(this, scene.getEngine(), name) || this;
  58101. // Members
  58102. /**
  58103. * The PassPostProcess id in the pipeline that contains the original scene color
  58104. * @type {string}
  58105. */
  58106. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  58107. /**
  58108. * The SSAO PostProcess id in the pipeline
  58109. * @type {string}
  58110. */
  58111. _this.SSAORenderEffect = "SSAORenderEffect";
  58112. /**
  58113. * The horizontal blur PostProcess id in the pipeline
  58114. * @type {string}
  58115. */
  58116. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  58117. /**
  58118. * The vertical blur PostProcess id in the pipeline
  58119. * @type {string}
  58120. */
  58121. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  58122. /**
  58123. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  58124. * @type {string}
  58125. */
  58126. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  58127. /**
  58128. * The output strength of the SSAO post-process. Default value is 1.0.
  58129. * @type {number}
  58130. */
  58131. _this.totalStrength = 1.0;
  58132. /**
  58133. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  58134. * @type {number}
  58135. */
  58136. _this.maxZ = 100.0;
  58137. /**
  58138. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  58139. * @type {number}
  58140. */
  58141. _this.minZAspect = 0.2;
  58142. /**
  58143. * Number of samples used for the SSAO calculations. Default value is 8
  58144. * @type {number}
  58145. */
  58146. _this._samples = 8;
  58147. /**
  58148. * Are we using bilateral blur ?
  58149. * @type {boolean}
  58150. */
  58151. _this._expensiveBlur = true;
  58152. /**
  58153. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  58154. * @type {number}
  58155. */
  58156. _this.radius = 2.0;
  58157. /**
  58158. * The base color of the SSAO post-process
  58159. * The final result is "base + ssao" between [0, 1]
  58160. * @type {number}
  58161. */
  58162. _this.base = 0.1;
  58163. _this._firstUpdate = true;
  58164. _this._scene = scene;
  58165. if (!_this.isSupported) {
  58166. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  58167. return _this;
  58168. }
  58169. var ssaoRatio = ratio.ssaoRatio || ratio;
  58170. var blurRatio = ratio.blurRatio || ratio;
  58171. // Set up assets
  58172. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  58173. _this._createRandomTexture();
  58174. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  58175. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  58176. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  58177. _this._createSSAOPostProcess(1.0);
  58178. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  58179. _this._createSSAOCombinePostProcess(blurRatio);
  58180. // Set up pipeline
  58181. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  58182. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  58183. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  58184. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  58185. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  58186. // Finish
  58187. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58188. if (cameras)
  58189. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  58190. return _this;
  58191. }
  58192. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  58193. get: function () {
  58194. return this._samples;
  58195. },
  58196. set: function (n) {
  58197. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  58198. this._samples = n;
  58199. this._sampleSphere = this._generateHemisphere();
  58200. this._firstUpdate = true;
  58201. },
  58202. enumerable: true,
  58203. configurable: true
  58204. });
  58205. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  58206. get: function () {
  58207. return this._expensiveBlur;
  58208. },
  58209. set: function (b) {
  58210. 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"]);
  58211. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  58212. this._expensiveBlur = b;
  58213. this._firstUpdate = true;
  58214. },
  58215. enumerable: true,
  58216. configurable: true
  58217. });
  58218. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  58219. /**
  58220. * Support test.
  58221. * @type {boolean}
  58222. */
  58223. get: function () {
  58224. var engine = BABYLON.Engine.LastCreatedEngine;
  58225. if (!engine) {
  58226. return false;
  58227. }
  58228. return engine.getCaps().drawBuffersExtension;
  58229. },
  58230. enumerable: true,
  58231. configurable: true
  58232. });
  58233. // Public Methods
  58234. /**
  58235. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  58236. */
  58237. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  58238. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  58239. for (var i = 0; i < this._scene.cameras.length; i++) {
  58240. var camera = this._scene.cameras[i];
  58241. this._originalColorPostProcess.dispose(camera);
  58242. this._ssaoPostProcess.dispose(camera);
  58243. this._blurHPostProcess.dispose(camera);
  58244. this._blurVPostProcess.dispose(camera);
  58245. this._ssaoCombinePostProcess.dispose(camera);
  58246. }
  58247. this._randomTexture.dispose();
  58248. if (disableGeometryBufferRenderer)
  58249. this._scene.disableGeometryBufferRenderer();
  58250. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  58251. _super.prototype.dispose.call(this);
  58252. };
  58253. // Private Methods
  58254. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  58255. var _this = this;
  58256. this._samplerOffsets = [];
  58257. var expensive = this.expensiveBlur;
  58258. for (var i = -8; i < 8; i++) {
  58259. this._samplerOffsets.push(i * 2 + 0.5);
  58260. }
  58261. 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");
  58262. this._blurHPostProcess.onApply = function (effect) {
  58263. if (!_this._scene.activeCamera) {
  58264. return;
  58265. }
  58266. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  58267. effect.setFloat("near", _this._scene.activeCamera.minZ);
  58268. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  58269. effect.setFloat("radius", _this.radius);
  58270. effect.setTexture("depthSampler", _this._depthTexture);
  58271. if (_this._firstUpdate) {
  58272. effect.setArray("samplerOffsets", _this._samplerOffsets);
  58273. }
  58274. };
  58275. 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");
  58276. this._blurVPostProcess.onApply = function (effect) {
  58277. if (!_this._scene.activeCamera) {
  58278. return;
  58279. }
  58280. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  58281. effect.setFloat("near", _this._scene.activeCamera.minZ);
  58282. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  58283. effect.setFloat("radius", _this.radius);
  58284. effect.setTexture("depthSampler", _this._depthTexture);
  58285. if (_this._firstUpdate) {
  58286. effect.setArray("samplerOffsets", _this._samplerOffsets);
  58287. _this._firstUpdate = false;
  58288. }
  58289. };
  58290. };
  58291. SSAO2RenderingPipeline.prototype._rebuild = function () {
  58292. this._firstUpdate = true;
  58293. _super.prototype._rebuild.call(this);
  58294. };
  58295. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  58296. var numSamples = this.samples;
  58297. var result = [];
  58298. var vector, scale;
  58299. var rand = function (min, max) {
  58300. return Math.random() * (max - min) + min;
  58301. };
  58302. var i = 0;
  58303. while (i < numSamples) {
  58304. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  58305. vector.normalize();
  58306. scale = i / numSamples;
  58307. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  58308. vector.scaleInPlace(scale);
  58309. result.push(vector.x, vector.y, vector.z);
  58310. i++;
  58311. }
  58312. return result;
  58313. };
  58314. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  58315. var _this = this;
  58316. var numSamples = this.samples;
  58317. this._sampleSphere = this._generateHemisphere();
  58318. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  58319. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  58320. "base", "range", "projection", "near", "far", "texelSize",
  58321. "xViewport", "yViewport", "maxZ", "minZAspect"
  58322. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  58323. this._ssaoPostProcess.onApply = function (effect) {
  58324. if (_this._firstUpdate) {
  58325. effect.setArray3("sampleSphere", _this._sampleSphere);
  58326. effect.setFloat("randTextureTiles", 4.0);
  58327. }
  58328. if (!_this._scene.activeCamera) {
  58329. return;
  58330. }
  58331. effect.setFloat("samplesFactor", 1 / _this.samples);
  58332. effect.setFloat("totalStrength", _this.totalStrength);
  58333. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  58334. effect.setFloat("radius", _this.radius);
  58335. effect.setFloat("maxZ", _this.maxZ);
  58336. effect.setFloat("minZAspect", _this.minZAspect);
  58337. effect.setFloat("base", _this.base);
  58338. effect.setFloat("near", _this._scene.activeCamera.minZ);
  58339. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  58340. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  58341. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  58342. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  58343. effect.setTexture("textureSampler", _this._depthTexture);
  58344. effect.setTexture("normalSampler", _this._normalTexture);
  58345. effect.setTexture("randomSampler", _this._randomTexture);
  58346. };
  58347. };
  58348. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  58349. var _this = this;
  58350. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58351. this._ssaoCombinePostProcess.onApply = function (effect) {
  58352. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  58353. };
  58354. };
  58355. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  58356. var size = 512;
  58357. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  58358. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58359. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58360. var context = this._randomTexture.getContext();
  58361. var rand = function (min, max) {
  58362. return Math.random() * (max - min) + min;
  58363. };
  58364. var randVector = BABYLON.Vector3.Zero();
  58365. for (var x = 0; x < size; x++) {
  58366. for (var y = 0; y < size; y++) {
  58367. randVector.x = rand(0.0, 1.0);
  58368. randVector.y = rand(0.0, 1.0);
  58369. randVector.z = 0.0;
  58370. randVector.normalize();
  58371. randVector.scaleInPlace(255);
  58372. randVector.x = Math.floor(randVector.x);
  58373. randVector.y = Math.floor(randVector.y);
  58374. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  58375. context.fillRect(x, y, 1, 1);
  58376. }
  58377. }
  58378. this._randomTexture.update(false);
  58379. };
  58380. __decorate([
  58381. BABYLON.serialize()
  58382. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  58383. __decorate([
  58384. BABYLON.serialize()
  58385. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  58386. __decorate([
  58387. BABYLON.serialize()
  58388. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  58389. __decorate([
  58390. BABYLON.serialize("samples")
  58391. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  58392. __decorate([
  58393. BABYLON.serialize("expensiveBlur")
  58394. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  58395. __decorate([
  58396. BABYLON.serialize()
  58397. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  58398. __decorate([
  58399. BABYLON.serialize()
  58400. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  58401. return SSAO2RenderingPipeline;
  58402. }(BABYLON.PostProcessRenderPipeline));
  58403. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  58404. })(BABYLON || (BABYLON = {}));
  58405. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  58406. // BABYLON.JS Chromatic Aberration GLSL Shader
  58407. // Author: Olivier Guyot
  58408. // Separates very slightly R, G and B colors on the edges of the screen
  58409. // Inspired by Francois Tarlier & Martins Upitis
  58410. var BABYLON;
  58411. (function (BABYLON) {
  58412. var LensRenderingPipeline = /** @class */ (function (_super) {
  58413. __extends(LensRenderingPipeline, _super);
  58414. /**
  58415. * @constructor
  58416. *
  58417. * Effect parameters are as follow:
  58418. * {
  58419. * chromatic_aberration: number; // from 0 to x (1 for realism)
  58420. * edge_blur: number; // from 0 to x (1 for realism)
  58421. * distortion: number; // from 0 to x (1 for realism)
  58422. * grain_amount: number; // from 0 to 1
  58423. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  58424. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  58425. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  58426. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  58427. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  58428. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  58429. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  58430. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  58431. * }
  58432. * Note: if an effect parameter is unset, effect is disabled
  58433. *
  58434. * @param {string} name - The rendering pipeline name
  58435. * @param {object} parameters - An object containing all parameters (see above)
  58436. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58437. * @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)
  58438. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58439. */
  58440. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  58441. if (ratio === void 0) { ratio = 1.0; }
  58442. var _this = _super.call(this, scene.getEngine(), name) || this;
  58443. // Lens effects can be of the following:
  58444. // - chromatic aberration (slight shift of RGB colors)
  58445. // - blur on the edge of the lens
  58446. // - lens distortion
  58447. // - depth-of-field blur & highlights enhancing
  58448. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  58449. // - grain effect (noise or custom texture)
  58450. // Two additional texture samplers are needed:
  58451. // - depth map (for depth-of-field)
  58452. // - grain texture
  58453. /**
  58454. * The chromatic aberration PostProcess id in the pipeline
  58455. * @type {string}
  58456. */
  58457. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  58458. /**
  58459. * The highlights enhancing PostProcess id in the pipeline
  58460. * @type {string}
  58461. */
  58462. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  58463. /**
  58464. * The depth-of-field PostProcess id in the pipeline
  58465. * @type {string}
  58466. */
  58467. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  58468. _this._scene = scene;
  58469. // Fetch texture samplers
  58470. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  58471. if (parameters.grain_texture) {
  58472. _this._grainTexture = parameters.grain_texture;
  58473. }
  58474. else {
  58475. _this._createGrainTexture();
  58476. }
  58477. // save parameters
  58478. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  58479. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  58480. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  58481. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  58482. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  58483. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  58484. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  58485. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  58486. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  58487. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  58488. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  58489. // Create effects
  58490. _this._createChromaticAberrationPostProcess(ratio);
  58491. _this._createHighlightsPostProcess(ratio);
  58492. _this._createDepthOfFieldPostProcess(ratio / 4);
  58493. // Set up pipeline
  58494. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  58495. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  58496. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  58497. if (_this._highlightsGain === -1) {
  58498. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  58499. }
  58500. // Finish
  58501. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58502. if (cameras) {
  58503. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  58504. }
  58505. return _this;
  58506. }
  58507. // public methods (self explanatory)
  58508. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  58509. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  58510. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  58511. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  58512. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  58513. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  58514. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  58515. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  58516. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  58517. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  58518. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  58519. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  58520. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  58521. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  58522. };
  58523. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  58524. this._highlightsPostProcess.updateEffect();
  58525. };
  58526. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  58527. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  58528. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  58529. this._highlightsGain = amount;
  58530. };
  58531. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  58532. if (this._highlightsGain === -1) {
  58533. this._highlightsGain = 1.0;
  58534. }
  58535. this._highlightsThreshold = amount;
  58536. };
  58537. LensRenderingPipeline.prototype.disableHighlights = function () {
  58538. this._highlightsGain = -1;
  58539. };
  58540. /**
  58541. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  58542. */
  58543. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  58544. if (disableDepthRender === void 0) { disableDepthRender = false; }
  58545. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  58546. this._chromaticAberrationPostProcess = null;
  58547. this._highlightsPostProcess = null;
  58548. this._depthOfFieldPostProcess = null;
  58549. this._grainTexture.dispose();
  58550. if (disableDepthRender)
  58551. this._scene.disableDepthRenderer();
  58552. };
  58553. // colors shifting and distortion
  58554. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  58555. var _this = this;
  58556. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  58557. [], // samplers
  58558. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58559. this._chromaticAberrationPostProcess.onApply = function (effect) {
  58560. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  58561. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  58562. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  58563. };
  58564. };
  58565. // highlights enhancing
  58566. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  58567. var _this = this;
  58568. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  58569. [], // samplers
  58570. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  58571. this._highlightsPostProcess.onApply = function (effect) {
  58572. effect.setFloat('gain', _this._highlightsGain);
  58573. effect.setFloat('threshold', _this._highlightsThreshold);
  58574. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  58575. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  58576. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  58577. };
  58578. };
  58579. // colors shifting and distortion
  58580. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  58581. var _this = this;
  58582. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  58583. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  58584. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  58585. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58586. this._depthOfFieldPostProcess.onApply = function (effect) {
  58587. effect.setTexture("depthSampler", _this._depthTexture);
  58588. effect.setTexture("grainSampler", _this._grainTexture);
  58589. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  58590. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  58591. effect.setFloat('grain_amount', _this._grainAmount);
  58592. effect.setBool('blur_noise', _this._blurNoise);
  58593. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  58594. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  58595. effect.setFloat('distortion', _this._distortion);
  58596. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  58597. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  58598. effect.setFloat('aperture', _this._dofAperture);
  58599. effect.setFloat('darken', _this._dofDarken);
  58600. effect.setFloat('edge_blur', _this._edgeBlur);
  58601. effect.setBool('highlights', (_this._highlightsGain !== -1));
  58602. if (_this._scene.activeCamera) {
  58603. effect.setFloat('near', _this._scene.activeCamera.minZ);
  58604. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  58605. }
  58606. };
  58607. };
  58608. // creates a black and white random noise texture, 512x512
  58609. LensRenderingPipeline.prototype._createGrainTexture = function () {
  58610. var size = 512;
  58611. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58612. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58613. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58614. var context = this._grainTexture.getContext();
  58615. var rand = function (min, max) {
  58616. return Math.random() * (max - min) + min;
  58617. };
  58618. var value;
  58619. for (var x = 0; x < size; x++) {
  58620. for (var y = 0; y < size; y++) {
  58621. value = Math.floor(rand(0.42, 0.58) * 255);
  58622. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  58623. context.fillRect(x, y, 1, 1);
  58624. }
  58625. }
  58626. this._grainTexture.update(false);
  58627. };
  58628. return LensRenderingPipeline;
  58629. }(BABYLON.PostProcessRenderPipeline));
  58630. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  58631. })(BABYLON || (BABYLON = {}));
  58632. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  58633. var BABYLON;
  58634. (function (BABYLON) {
  58635. var StandardRenderingPipeline = /** @class */ (function (_super) {
  58636. __extends(StandardRenderingPipeline, _super);
  58637. /**
  58638. * @constructor
  58639. * @param {string} name - The rendering pipeline name
  58640. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58641. * @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)
  58642. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  58643. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58644. */
  58645. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  58646. if (originalPostProcess === void 0) { originalPostProcess = null; }
  58647. var _this = _super.call(this, scene.getEngine(), name) || this;
  58648. _this.downSampleX4PostProcess = null;
  58649. _this.brightPassPostProcess = null;
  58650. _this.blurHPostProcesses = [];
  58651. _this.blurVPostProcesses = [];
  58652. _this.textureAdderPostProcess = null;
  58653. _this.volumetricLightPostProcess = null;
  58654. _this.volumetricLightSmoothXPostProcess = null;
  58655. _this.volumetricLightSmoothYPostProcess = null;
  58656. _this.volumetricLightMergePostProces = null;
  58657. _this.volumetricLightFinalPostProcess = null;
  58658. _this.luminancePostProcess = null;
  58659. _this.luminanceDownSamplePostProcesses = [];
  58660. _this.hdrPostProcess = null;
  58661. _this.textureAdderFinalPostProcess = null;
  58662. _this.lensFlareFinalPostProcess = null;
  58663. _this.hdrFinalPostProcess = null;
  58664. _this.lensFlarePostProcess = null;
  58665. _this.lensFlareComposePostProcess = null;
  58666. _this.motionBlurPostProcess = null;
  58667. _this.depthOfFieldPostProcess = null;
  58668. // Values
  58669. _this.brightThreshold = 1.0;
  58670. _this.blurWidth = 512.0;
  58671. _this.horizontalBlur = false;
  58672. _this.exposure = 1.0;
  58673. _this.lensTexture = null;
  58674. _this.volumetricLightCoefficient = 0.2;
  58675. _this.volumetricLightPower = 4.0;
  58676. _this.volumetricLightBlurScale = 64.0;
  58677. _this.sourceLight = null;
  58678. _this.hdrMinimumLuminance = 1.0;
  58679. _this.hdrDecreaseRate = 0.5;
  58680. _this.hdrIncreaseRate = 0.5;
  58681. _this.lensColorTexture = null;
  58682. _this.lensFlareStrength = 20.0;
  58683. _this.lensFlareGhostDispersal = 1.4;
  58684. _this.lensFlareHaloWidth = 0.7;
  58685. _this.lensFlareDistortionStrength = 16.0;
  58686. _this.lensStarTexture = null;
  58687. _this.lensFlareDirtTexture = null;
  58688. _this.depthOfFieldDistance = 10.0;
  58689. _this.depthOfFieldBlurWidth = 64.0;
  58690. _this.motionStrength = 1.0;
  58691. // IAnimatable
  58692. _this.animations = [];
  58693. _this._currentDepthOfFieldSource = null;
  58694. _this._hdrCurrentLuminance = 1.0;
  58695. // Getters and setters
  58696. _this._bloomEnabled = true;
  58697. _this._depthOfFieldEnabled = false;
  58698. _this._vlsEnabled = false;
  58699. _this._lensFlareEnabled = false;
  58700. _this._hdrEnabled = false;
  58701. _this._motionBlurEnabled = false;
  58702. _this._motionBlurSamples = 64.0;
  58703. _this._volumetricLightStepsCount = 50.0;
  58704. _this._cameras = cameras || [];
  58705. // Initialize
  58706. _this._scene = scene;
  58707. _this._basePostProcess = originalPostProcess;
  58708. _this._ratio = ratio;
  58709. // Misc
  58710. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58711. // Finish
  58712. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58713. _this._buildPipeline();
  58714. return _this;
  58715. }
  58716. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  58717. get: function () {
  58718. return this._bloomEnabled;
  58719. },
  58720. set: function (enabled) {
  58721. if (this._bloomEnabled === enabled) {
  58722. return;
  58723. }
  58724. this._bloomEnabled = enabled;
  58725. this._buildPipeline();
  58726. },
  58727. enumerable: true,
  58728. configurable: true
  58729. });
  58730. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  58731. get: function () {
  58732. return this._depthOfFieldEnabled;
  58733. },
  58734. set: function (enabled) {
  58735. if (this._depthOfFieldEnabled === enabled) {
  58736. return;
  58737. }
  58738. this._depthOfFieldEnabled = enabled;
  58739. this._buildPipeline();
  58740. },
  58741. enumerable: true,
  58742. configurable: true
  58743. });
  58744. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  58745. get: function () {
  58746. return this._lensFlareEnabled;
  58747. },
  58748. set: function (enabled) {
  58749. if (this._lensFlareEnabled === enabled) {
  58750. return;
  58751. }
  58752. this._lensFlareEnabled = enabled;
  58753. this._buildPipeline();
  58754. },
  58755. enumerable: true,
  58756. configurable: true
  58757. });
  58758. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  58759. get: function () {
  58760. return this._hdrEnabled;
  58761. },
  58762. set: function (enabled) {
  58763. if (this._hdrEnabled === enabled) {
  58764. return;
  58765. }
  58766. this._hdrEnabled = enabled;
  58767. this._buildPipeline();
  58768. },
  58769. enumerable: true,
  58770. configurable: true
  58771. });
  58772. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  58773. get: function () {
  58774. return this._vlsEnabled;
  58775. },
  58776. set: function (enabled) {
  58777. if (this._vlsEnabled === enabled) {
  58778. return;
  58779. }
  58780. if (enabled) {
  58781. var geometry = this._scene.enableGeometryBufferRenderer();
  58782. if (!geometry) {
  58783. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  58784. return;
  58785. }
  58786. }
  58787. this._vlsEnabled = enabled;
  58788. this._buildPipeline();
  58789. },
  58790. enumerable: true,
  58791. configurable: true
  58792. });
  58793. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  58794. get: function () {
  58795. return this._motionBlurEnabled;
  58796. },
  58797. set: function (enabled) {
  58798. if (this._motionBlurEnabled === enabled) {
  58799. return;
  58800. }
  58801. this._motionBlurEnabled = enabled;
  58802. this._buildPipeline();
  58803. },
  58804. enumerable: true,
  58805. configurable: true
  58806. });
  58807. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  58808. get: function () {
  58809. return this._volumetricLightStepsCount;
  58810. },
  58811. set: function (count) {
  58812. if (this.volumetricLightPostProcess) {
  58813. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  58814. }
  58815. this._volumetricLightStepsCount = count;
  58816. },
  58817. enumerable: true,
  58818. configurable: true
  58819. });
  58820. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  58821. get: function () {
  58822. return this._motionBlurSamples;
  58823. },
  58824. set: function (samples) {
  58825. if (this.motionBlurPostProcess) {
  58826. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  58827. }
  58828. this._motionBlurSamples = samples;
  58829. },
  58830. enumerable: true,
  58831. configurable: true
  58832. });
  58833. StandardRenderingPipeline.prototype._buildPipeline = function () {
  58834. var _this = this;
  58835. var ratio = this._ratio;
  58836. var scene = this._scene;
  58837. this._disposePostProcesses();
  58838. this._reset();
  58839. // Create pass post-process
  58840. if (!this._basePostProcess) {
  58841. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  58842. this.originalPostProcess.onApply = function (effect) {
  58843. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  58844. };
  58845. }
  58846. else {
  58847. this.originalPostProcess = this._basePostProcess;
  58848. }
  58849. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  58850. this._currentDepthOfFieldSource = this.originalPostProcess;
  58851. if (this._vlsEnabled) {
  58852. // Create volumetric light
  58853. this._createVolumetricLightPostProcess(scene, ratio);
  58854. // Create volumetric light final post-process
  58855. 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);
  58856. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  58857. }
  58858. if (this._bloomEnabled) {
  58859. // Create down sample X4 post-process
  58860. this._createDownSampleX4PostProcess(scene, ratio / 2);
  58861. // Create bright pass post-process
  58862. this._createBrightPassPostProcess(scene, ratio / 2);
  58863. // Create gaussian blur post-processes (down sampling blurs)
  58864. this._createBlurPostProcesses(scene, ratio / 4, 1);
  58865. // Create texture adder post-process
  58866. this._createTextureAdderPostProcess(scene, ratio);
  58867. // Create depth-of-field source post-process
  58868. 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);
  58869. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  58870. }
  58871. if (this._lensFlareEnabled) {
  58872. // Create lens flare post-process
  58873. this._createLensFlarePostProcess(scene, ratio);
  58874. // Create depth-of-field source post-process post lens-flare and disable it now
  58875. 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);
  58876. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  58877. }
  58878. if (this._hdrEnabled) {
  58879. // Create luminance
  58880. this._createLuminancePostProcesses(scene, this._floatTextureType);
  58881. // Create HDR
  58882. this._createHdrPostProcess(scene, ratio);
  58883. // Create depth-of-field source post-process post hdr and disable it now
  58884. 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);
  58885. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  58886. }
  58887. if (this._depthOfFieldEnabled) {
  58888. // Create gaussian blur used by depth-of-field
  58889. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  58890. // Create depth-of-field post-process
  58891. this._createDepthOfFieldPostProcess(scene, ratio);
  58892. }
  58893. if (this._motionBlurEnabled) {
  58894. // Create motion blur post-process
  58895. this._createMotionBlurPostProcess(scene, ratio);
  58896. }
  58897. if (this._cameras !== null) {
  58898. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  58899. }
  58900. };
  58901. // Down Sample X4 Post-Processs
  58902. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  58903. var _this = this;
  58904. var downSampleX4Offsets = new Array(32);
  58905. 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);
  58906. this.downSampleX4PostProcess.onApply = function (effect) {
  58907. var id = 0;
  58908. var width = _this.downSampleX4PostProcess.width;
  58909. var height = _this.downSampleX4PostProcess.height;
  58910. for (var i = -2; i < 2; i++) {
  58911. for (var j = -2; j < 2; j++) {
  58912. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  58913. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  58914. id += 2;
  58915. }
  58916. }
  58917. effect.setArray2("dsOffsets", downSampleX4Offsets);
  58918. };
  58919. // Add to pipeline
  58920. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  58921. };
  58922. // Brightpass Post-Process
  58923. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  58924. var _this = this;
  58925. var brightOffsets = new Array(8);
  58926. 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);
  58927. this.brightPassPostProcess.onApply = function (effect) {
  58928. var sU = (1.0 / _this.brightPassPostProcess.width);
  58929. var sV = (1.0 / _this.brightPassPostProcess.height);
  58930. brightOffsets[0] = -0.5 * sU;
  58931. brightOffsets[1] = 0.5 * sV;
  58932. brightOffsets[2] = 0.5 * sU;
  58933. brightOffsets[3] = 0.5 * sV;
  58934. brightOffsets[4] = -0.5 * sU;
  58935. brightOffsets[5] = -0.5 * sV;
  58936. brightOffsets[6] = 0.5 * sU;
  58937. brightOffsets[7] = -0.5 * sV;
  58938. effect.setArray2("dsOffsets", brightOffsets);
  58939. effect.setFloat("brightThreshold", _this.brightThreshold);
  58940. };
  58941. // Add to pipeline
  58942. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  58943. };
  58944. // Create blur H&V post-processes
  58945. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  58946. var _this = this;
  58947. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  58948. var engine = scene.getEngine();
  58949. 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);
  58950. 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);
  58951. blurX.onActivateObservable.add(function () {
  58952. var dw = blurX.width / engine.getRenderWidth();
  58953. blurX.kernel = _this[blurWidthKey] * dw;
  58954. });
  58955. blurY.onActivateObservable.add(function () {
  58956. var dw = blurY.height / engine.getRenderHeight();
  58957. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  58958. });
  58959. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  58960. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  58961. this.blurHPostProcesses.push(blurX);
  58962. this.blurVPostProcesses.push(blurY);
  58963. };
  58964. // Create texture adder post-process
  58965. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  58966. var _this = this;
  58967. 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);
  58968. this.textureAdderPostProcess.onApply = function (effect) {
  58969. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  58970. effect.setTexture("lensSampler", _this.lensTexture);
  58971. effect.setFloat("exposure", _this.exposure);
  58972. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  58973. };
  58974. // Add to pipeline
  58975. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  58976. };
  58977. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  58978. var _this = this;
  58979. var geometryRenderer = scene.enableGeometryBufferRenderer();
  58980. geometryRenderer.enablePosition = true;
  58981. var geometry = geometryRenderer.getGBuffer();
  58982. // Base post-process
  58983. 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));
  58984. var depthValues = BABYLON.Vector2.Zero();
  58985. this.volumetricLightPostProcess.onApply = function (effect) {
  58986. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  58987. var generator = _this.sourceLight.getShadowGenerator();
  58988. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  58989. effect.setTexture("positionSampler", geometry.textures[2]);
  58990. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  58991. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  58992. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  58993. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  58994. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  58995. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  58996. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  58997. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  58998. effect.setVector2("depthValues", depthValues);
  58999. }
  59000. };
  59001. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  59002. // Smooth
  59003. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  59004. // Merge
  59005. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  59006. this.volumetricLightMergePostProces.onApply = function (effect) {
  59007. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  59008. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  59009. };
  59010. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  59011. };
  59012. // Create luminance
  59013. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  59014. var _this = this;
  59015. // Create luminance
  59016. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  59017. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  59018. var offsets = [];
  59019. this.luminancePostProcess.onApply = function (effect) {
  59020. var sU = (1.0 / _this.luminancePostProcess.width);
  59021. var sV = (1.0 / _this.luminancePostProcess.height);
  59022. offsets[0] = -0.5 * sU;
  59023. offsets[1] = 0.5 * sV;
  59024. offsets[2] = 0.5 * sU;
  59025. offsets[3] = 0.5 * sV;
  59026. offsets[4] = -0.5 * sU;
  59027. offsets[5] = -0.5 * sV;
  59028. offsets[6] = 0.5 * sU;
  59029. offsets[7] = -0.5 * sV;
  59030. effect.setArray2("lumOffsets", offsets);
  59031. };
  59032. // Add to pipeline
  59033. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  59034. // Create down sample luminance
  59035. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  59036. var size = Math.pow(3, i);
  59037. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  59038. if (i === 0) {
  59039. defines += "#define FINAL_DOWN_SAMPLER";
  59040. }
  59041. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  59042. this.luminanceDownSamplePostProcesses.push(postProcess);
  59043. }
  59044. // Create callbacks and add effects
  59045. var lastLuminance = this.luminancePostProcess;
  59046. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  59047. var downSampleOffsets = new Array(18);
  59048. pp.onApply = function (effect) {
  59049. if (!lastLuminance) {
  59050. return;
  59051. }
  59052. var id = 0;
  59053. for (var x = -1; x < 2; x++) {
  59054. for (var y = -1; y < 2; y++) {
  59055. downSampleOffsets[id] = x / lastLuminance.width;
  59056. downSampleOffsets[id + 1] = y / lastLuminance.height;
  59057. id += 2;
  59058. }
  59059. }
  59060. effect.setArray2("dsOffsets", downSampleOffsets);
  59061. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  59062. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  59063. lastLuminance = _this.luminancePostProcess;
  59064. }
  59065. else {
  59066. lastLuminance = pp;
  59067. }
  59068. };
  59069. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  59070. pp.onAfterRender = function (effect) {
  59071. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  59072. 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);
  59073. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  59074. };
  59075. }
  59076. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  59077. });
  59078. };
  59079. // Create HDR post-process
  59080. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  59081. var _this = this;
  59082. 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);
  59083. var outputLiminance = 1;
  59084. var time = 0;
  59085. var lastTime = 0;
  59086. this.hdrPostProcess.onApply = function (effect) {
  59087. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  59088. time += scene.getEngine().getDeltaTime();
  59089. if (outputLiminance < 0) {
  59090. outputLiminance = _this._hdrCurrentLuminance;
  59091. }
  59092. else {
  59093. var dt = (lastTime - time) / 1000.0;
  59094. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  59095. outputLiminance += _this.hdrDecreaseRate * dt;
  59096. }
  59097. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  59098. outputLiminance -= _this.hdrIncreaseRate * dt;
  59099. }
  59100. else {
  59101. outputLiminance = _this._hdrCurrentLuminance;
  59102. }
  59103. }
  59104. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  59105. effect.setFloat("averageLuminance", outputLiminance);
  59106. lastTime = time;
  59107. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  59108. };
  59109. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  59110. };
  59111. // Create lens flare post-process
  59112. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  59113. var _this = this;
  59114. 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);
  59115. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  59116. this._createBlurPostProcesses(scene, ratio / 4, 2);
  59117. 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);
  59118. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  59119. var resolution = new BABYLON.Vector2(0, 0);
  59120. // Lens flare
  59121. this.lensFlarePostProcess.onApply = function (effect) {
  59122. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  59123. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  59124. effect.setFloat("strength", _this.lensFlareStrength);
  59125. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  59126. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  59127. // Shift
  59128. resolution.x = _this.lensFlarePostProcess.width;
  59129. resolution.y = _this.lensFlarePostProcess.height;
  59130. effect.setVector2("resolution", resolution);
  59131. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  59132. };
  59133. // Compose
  59134. 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);
  59135. 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);
  59136. this.lensFlareComposePostProcess.onApply = function (effect) {
  59137. if (!_this._scene.activeCamera) {
  59138. return;
  59139. }
  59140. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  59141. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  59142. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  59143. // Lens start rotation matrix
  59144. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  59145. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  59146. 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));
  59147. camRot *= 4.0;
  59148. 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);
  59149. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  59150. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  59151. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  59152. };
  59153. };
  59154. // Create depth-of-field post-process
  59155. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  59156. var _this = this;
  59157. 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);
  59158. this.depthOfFieldPostProcess.onApply = function (effect) {
  59159. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  59160. effect.setTexture("depthSampler", _this._getDepthTexture());
  59161. effect.setFloat("distance", _this.depthOfFieldDistance);
  59162. };
  59163. // Add to pipeline
  59164. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  59165. };
  59166. // Create motion blur post-process
  59167. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  59168. var _this = this;
  59169. 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);
  59170. var motionScale = 0;
  59171. var prevViewProjection = BABYLON.Matrix.Identity();
  59172. var invViewProjection = BABYLON.Matrix.Identity();
  59173. var viewProjection = BABYLON.Matrix.Identity();
  59174. var screenSize = BABYLON.Vector2.Zero();
  59175. this.motionBlurPostProcess.onApply = function (effect) {
  59176. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  59177. viewProjection.invertToRef(invViewProjection);
  59178. effect.setMatrix("inverseViewProjection", invViewProjection);
  59179. effect.setMatrix("prevViewProjection", prevViewProjection);
  59180. prevViewProjection = viewProjection;
  59181. screenSize.x = _this.motionBlurPostProcess.width;
  59182. screenSize.y = _this.motionBlurPostProcess.height;
  59183. effect.setVector2("screenSize", screenSize);
  59184. motionScale = scene.getEngine().getFps() / 60.0;
  59185. effect.setFloat("motionScale", motionScale);
  59186. effect.setFloat("motionStrength", _this.motionStrength);
  59187. effect.setTexture("depthSampler", _this._getDepthTexture());
  59188. };
  59189. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  59190. };
  59191. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  59192. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  59193. var renderer = this._scene.enableGeometryBufferRenderer();
  59194. return renderer.getGBuffer().textures[0];
  59195. }
  59196. return this._scene.enableDepthRenderer().getDepthMap();
  59197. };
  59198. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  59199. for (var i = 0; i < this._cameras.length; i++) {
  59200. var camera = this._cameras[i];
  59201. if (this.originalPostProcess) {
  59202. this.originalPostProcess.dispose(camera);
  59203. }
  59204. if (this.downSampleX4PostProcess) {
  59205. this.downSampleX4PostProcess.dispose(camera);
  59206. }
  59207. if (this.brightPassPostProcess) {
  59208. this.brightPassPostProcess.dispose(camera);
  59209. }
  59210. if (this.textureAdderPostProcess) {
  59211. this.textureAdderPostProcess.dispose(camera);
  59212. }
  59213. if (this.textureAdderFinalPostProcess) {
  59214. this.textureAdderFinalPostProcess.dispose(camera);
  59215. }
  59216. if (this.volumetricLightPostProcess) {
  59217. this.volumetricLightPostProcess.dispose(camera);
  59218. }
  59219. if (this.volumetricLightSmoothXPostProcess) {
  59220. this.volumetricLightSmoothXPostProcess.dispose(camera);
  59221. }
  59222. if (this.volumetricLightSmoothYPostProcess) {
  59223. this.volumetricLightSmoothYPostProcess.dispose(camera);
  59224. }
  59225. if (this.volumetricLightMergePostProces) {
  59226. this.volumetricLightMergePostProces.dispose(camera);
  59227. }
  59228. if (this.volumetricLightFinalPostProcess) {
  59229. this.volumetricLightFinalPostProcess.dispose(camera);
  59230. }
  59231. if (this.lensFlarePostProcess) {
  59232. this.lensFlarePostProcess.dispose(camera);
  59233. }
  59234. if (this.lensFlareComposePostProcess) {
  59235. this.lensFlareComposePostProcess.dispose(camera);
  59236. }
  59237. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  59238. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  59239. }
  59240. if (this.luminancePostProcess) {
  59241. this.luminancePostProcess.dispose(camera);
  59242. }
  59243. if (this.hdrPostProcess) {
  59244. this.hdrPostProcess.dispose(camera);
  59245. }
  59246. if (this.hdrFinalPostProcess) {
  59247. this.hdrFinalPostProcess.dispose(camera);
  59248. }
  59249. if (this.depthOfFieldPostProcess) {
  59250. this.depthOfFieldPostProcess.dispose(camera);
  59251. }
  59252. if (this.motionBlurPostProcess) {
  59253. this.motionBlurPostProcess.dispose(camera);
  59254. }
  59255. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  59256. this.blurHPostProcesses[j].dispose(camera);
  59257. }
  59258. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  59259. this.blurVPostProcesses[j].dispose(camera);
  59260. }
  59261. }
  59262. this.originalPostProcess = null;
  59263. this.downSampleX4PostProcess = null;
  59264. this.brightPassPostProcess = null;
  59265. this.textureAdderPostProcess = null;
  59266. this.textureAdderFinalPostProcess = null;
  59267. this.volumetricLightPostProcess = null;
  59268. this.volumetricLightSmoothXPostProcess = null;
  59269. this.volumetricLightSmoothYPostProcess = null;
  59270. this.volumetricLightMergePostProces = null;
  59271. this.volumetricLightFinalPostProcess = null;
  59272. this.lensFlarePostProcess = null;
  59273. this.lensFlareComposePostProcess = null;
  59274. this.luminancePostProcess = null;
  59275. this.hdrPostProcess = null;
  59276. this.hdrFinalPostProcess = null;
  59277. this.depthOfFieldPostProcess = null;
  59278. this.motionBlurPostProcess = null;
  59279. this.luminanceDownSamplePostProcesses = [];
  59280. this.blurHPostProcesses = [];
  59281. this.blurVPostProcesses = [];
  59282. };
  59283. // Dispose
  59284. StandardRenderingPipeline.prototype.dispose = function () {
  59285. this._disposePostProcesses();
  59286. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  59287. _super.prototype.dispose.call(this);
  59288. };
  59289. // Serialize rendering pipeline
  59290. StandardRenderingPipeline.prototype.serialize = function () {
  59291. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59292. serializationObject.customType = "StandardRenderingPipeline";
  59293. return serializationObject;
  59294. };
  59295. /**
  59296. * Static members
  59297. */
  59298. // Parse serialized pipeline
  59299. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  59300. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  59301. };
  59302. // Luminance steps
  59303. StandardRenderingPipeline.LuminanceSteps = 6;
  59304. __decorate([
  59305. BABYLON.serialize()
  59306. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  59307. __decorate([
  59308. BABYLON.serialize()
  59309. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  59310. __decorate([
  59311. BABYLON.serialize()
  59312. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  59313. __decorate([
  59314. BABYLON.serialize()
  59315. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  59316. __decorate([
  59317. BABYLON.serializeAsTexture("lensTexture")
  59318. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  59319. __decorate([
  59320. BABYLON.serialize()
  59321. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  59322. __decorate([
  59323. BABYLON.serialize()
  59324. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  59325. __decorate([
  59326. BABYLON.serialize()
  59327. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  59328. __decorate([
  59329. BABYLON.serialize()
  59330. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  59331. __decorate([
  59332. BABYLON.serialize()
  59333. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  59334. __decorate([
  59335. BABYLON.serialize()
  59336. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  59337. __decorate([
  59338. BABYLON.serializeAsTexture("lensColorTexture")
  59339. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  59340. __decorate([
  59341. BABYLON.serialize()
  59342. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  59343. __decorate([
  59344. BABYLON.serialize()
  59345. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  59346. __decorate([
  59347. BABYLON.serialize()
  59348. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  59349. __decorate([
  59350. BABYLON.serialize()
  59351. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  59352. __decorate([
  59353. BABYLON.serializeAsTexture("lensStarTexture")
  59354. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  59355. __decorate([
  59356. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  59357. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  59358. __decorate([
  59359. BABYLON.serialize()
  59360. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  59361. __decorate([
  59362. BABYLON.serialize()
  59363. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  59364. __decorate([
  59365. BABYLON.serialize()
  59366. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  59367. __decorate([
  59368. BABYLON.serialize()
  59369. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  59370. __decorate([
  59371. BABYLON.serialize()
  59372. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  59373. __decorate([
  59374. BABYLON.serialize()
  59375. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  59376. __decorate([
  59377. BABYLON.serialize()
  59378. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  59379. __decorate([
  59380. BABYLON.serialize()
  59381. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  59382. __decorate([
  59383. BABYLON.serialize()
  59384. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  59385. __decorate([
  59386. BABYLON.serialize()
  59387. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  59388. __decorate([
  59389. BABYLON.serialize()
  59390. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  59391. return StandardRenderingPipeline;
  59392. }(BABYLON.PostProcessRenderPipeline));
  59393. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  59394. })(BABYLON || (BABYLON = {}));
  59395. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  59396. var BABYLON;
  59397. (function (BABYLON) {
  59398. var FxaaPostProcess = /** @class */ (function (_super) {
  59399. __extends(FxaaPostProcess, _super);
  59400. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59401. if (camera === void 0) { camera = null; }
  59402. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59403. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  59404. _this.onApplyObservable.add(function (effect) {
  59405. var texelSize = _this.texelSize;
  59406. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  59407. });
  59408. return _this;
  59409. }
  59410. return FxaaPostProcess;
  59411. }(BABYLON.PostProcess));
  59412. BABYLON.FxaaPostProcess = FxaaPostProcess;
  59413. })(BABYLON || (BABYLON = {}));
  59414. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  59415. var BABYLON;
  59416. (function (BABYLON) {
  59417. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  59418. __extends(DefaultRenderingPipeline, _super);
  59419. /**
  59420. * @constructor
  59421. * @param {string} name - The rendering pipeline name
  59422. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  59423. * @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)
  59424. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  59425. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  59426. */
  59427. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  59428. if (automaticBuild === void 0) { automaticBuild = true; }
  59429. var _this = _super.call(this, scene.getEngine(), name) || this;
  59430. _this.PassPostProcessId = "PassPostProcessEffect";
  59431. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  59432. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  59433. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  59434. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  59435. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  59436. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  59437. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  59438. // IAnimatable
  59439. _this.animations = [];
  59440. // Values
  59441. _this._bloomEnabled = false;
  59442. _this._fxaaEnabled = false;
  59443. _this._imageProcessingEnabled = true;
  59444. _this._bloomScale = 0.6;
  59445. _this._buildAllowed = true;
  59446. /**
  59447. * Specifies the size of the bloom blur kernel, relative to the final output size
  59448. */
  59449. _this.bloomKernel = 64;
  59450. /**
  59451. * Specifies the weight of the bloom in the final rendering
  59452. */
  59453. _this._bloomWeight = 0.15;
  59454. _this._cameras = cameras || [];
  59455. _this._buildAllowed = automaticBuild;
  59456. // Initialize
  59457. _this._scene = scene;
  59458. var caps = _this._scene.getEngine().getCaps();
  59459. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  59460. // Misc
  59461. if (_this._hdr) {
  59462. if (caps.textureHalfFloatRender) {
  59463. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59464. }
  59465. else if (caps.textureFloatRender) {
  59466. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59467. }
  59468. }
  59469. else {
  59470. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59471. }
  59472. // Attach
  59473. scene.postProcessRenderPipelineManager.addPipeline(_this);
  59474. _this._buildPipeline();
  59475. return _this;
  59476. }
  59477. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  59478. get: function () {
  59479. return this._bloomWeight;
  59480. },
  59481. set: function (value) {
  59482. if (this._bloomWeight === value) {
  59483. return;
  59484. }
  59485. this._bloomWeight = value;
  59486. if (this._hdr && this.copyBack) {
  59487. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  59488. }
  59489. },
  59490. enumerable: true,
  59491. configurable: true
  59492. });
  59493. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  59494. get: function () {
  59495. return this._bloomScale;
  59496. },
  59497. set: function (value) {
  59498. if (this._bloomScale === value) {
  59499. return;
  59500. }
  59501. this._bloomScale = value;
  59502. this._buildPipeline();
  59503. },
  59504. enumerable: true,
  59505. configurable: true
  59506. });
  59507. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  59508. get: function () {
  59509. return this._bloomEnabled;
  59510. },
  59511. set: function (enabled) {
  59512. if (this._bloomEnabled === enabled) {
  59513. return;
  59514. }
  59515. this._bloomEnabled = enabled;
  59516. this._buildPipeline();
  59517. },
  59518. enumerable: true,
  59519. configurable: true
  59520. });
  59521. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  59522. get: function () {
  59523. return this._fxaaEnabled;
  59524. },
  59525. set: function (enabled) {
  59526. if (this._fxaaEnabled === enabled) {
  59527. return;
  59528. }
  59529. this._fxaaEnabled = enabled;
  59530. this._buildPipeline();
  59531. },
  59532. enumerable: true,
  59533. configurable: true
  59534. });
  59535. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  59536. get: function () {
  59537. return this._imageProcessingEnabled;
  59538. },
  59539. set: function (enabled) {
  59540. if (this._imageProcessingEnabled === enabled) {
  59541. return;
  59542. }
  59543. this._imageProcessingEnabled = enabled;
  59544. this._buildPipeline();
  59545. },
  59546. enumerable: true,
  59547. configurable: true
  59548. });
  59549. /**
  59550. * Force the compilation of the entire pipeline.
  59551. */
  59552. DefaultRenderingPipeline.prototype.prepare = function () {
  59553. var previousState = this._buildAllowed;
  59554. this._buildAllowed = true;
  59555. this._buildPipeline();
  59556. this._buildAllowed = previousState;
  59557. };
  59558. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  59559. var _this = this;
  59560. if (!this._buildAllowed) {
  59561. return;
  59562. }
  59563. var engine = this._scene.getEngine();
  59564. this._disposePostProcesses();
  59565. this._reset();
  59566. if (this.bloomEnabled) {
  59567. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59568. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  59569. if (!this._hdr) {
  59570. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59571. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  59572. this.highlights.autoClear = false;
  59573. this.highlights.alwaysForcePOT = true;
  59574. }
  59575. 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);
  59576. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  59577. this.blurX.alwaysForcePOT = true;
  59578. this.blurX.autoClear = false;
  59579. this.blurX.onActivateObservable.add(function () {
  59580. var dw = _this.blurX.width / engine.getRenderWidth(true);
  59581. _this.blurX.kernel = _this.bloomKernel * dw;
  59582. });
  59583. 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);
  59584. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  59585. this.blurY.alwaysForcePOT = true;
  59586. this.blurY.autoClear = false;
  59587. this.blurY.onActivateObservable.add(function () {
  59588. var dh = _this.blurY.height / engine.getRenderHeight(true);
  59589. _this.blurY.kernel = _this.bloomKernel * dh;
  59590. });
  59591. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59592. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  59593. this.copyBack.alwaysForcePOT = true;
  59594. if (this._hdr) {
  59595. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  59596. var w = this.bloomWeight;
  59597. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  59598. }
  59599. else {
  59600. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  59601. }
  59602. this.copyBack.autoClear = false;
  59603. }
  59604. if (this._imageProcessingEnabled) {
  59605. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59606. if (this._hdr) {
  59607. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  59608. }
  59609. else {
  59610. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  59611. }
  59612. }
  59613. if (this.fxaaEnabled) {
  59614. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59615. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  59616. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  59617. }
  59618. else {
  59619. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59620. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  59621. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  59622. }
  59623. if (this.bloomEnabled) {
  59624. if (this._hdr) {
  59625. this.copyBack.shareOutputWith(this.blurX);
  59626. if (this.imageProcessing) {
  59627. this.imageProcessing.shareOutputWith(this.pass);
  59628. this.imageProcessing.autoClear = false;
  59629. }
  59630. else if (this.fxaa) {
  59631. this.fxaa.shareOutputWith(this.pass);
  59632. }
  59633. else {
  59634. this.finalMerge.shareOutputWith(this.pass);
  59635. }
  59636. }
  59637. else {
  59638. if (this.fxaa) {
  59639. this.fxaa.shareOutputWith(this.pass);
  59640. }
  59641. else {
  59642. this.finalMerge.shareOutputWith(this.pass);
  59643. }
  59644. }
  59645. }
  59646. if (this._cameras !== null) {
  59647. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  59648. }
  59649. };
  59650. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  59651. for (var i = 0; i < this._cameras.length; i++) {
  59652. var camera = this._cameras[i];
  59653. if (this.pass) {
  59654. this.pass.dispose(camera);
  59655. }
  59656. if (this.highlights) {
  59657. this.highlights.dispose(camera);
  59658. }
  59659. if (this.blurX) {
  59660. this.blurX.dispose(camera);
  59661. }
  59662. if (this.blurY) {
  59663. this.blurY.dispose(camera);
  59664. }
  59665. if (this.copyBack) {
  59666. this.copyBack.dispose(camera);
  59667. }
  59668. if (this.imageProcessing) {
  59669. this.imageProcessing.dispose(camera);
  59670. }
  59671. if (this.fxaa) {
  59672. this.fxaa.dispose(camera);
  59673. }
  59674. if (this.finalMerge) {
  59675. this.finalMerge.dispose(camera);
  59676. }
  59677. }
  59678. this.pass = null;
  59679. this.highlights = null;
  59680. this.blurX = null;
  59681. this.blurY = null;
  59682. this.copyBack = null;
  59683. this.imageProcessing = null;
  59684. this.fxaa = null;
  59685. this.finalMerge = null;
  59686. };
  59687. // Dispose
  59688. DefaultRenderingPipeline.prototype.dispose = function () {
  59689. this._disposePostProcesses();
  59690. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  59691. _super.prototype.dispose.call(this);
  59692. };
  59693. // Serialize rendering pipeline
  59694. DefaultRenderingPipeline.prototype.serialize = function () {
  59695. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59696. serializationObject.customType = "DefaultRenderingPipeline";
  59697. return serializationObject;
  59698. };
  59699. // Parse serialized pipeline
  59700. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  59701. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  59702. };
  59703. __decorate([
  59704. BABYLON.serialize()
  59705. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  59706. __decorate([
  59707. BABYLON.serialize()
  59708. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  59709. __decorate([
  59710. BABYLON.serialize()
  59711. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  59712. __decorate([
  59713. BABYLON.serialize()
  59714. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  59715. __decorate([
  59716. BABYLON.serialize()
  59717. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  59718. __decorate([
  59719. BABYLON.serialize()
  59720. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  59721. __decorate([
  59722. BABYLON.serialize()
  59723. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  59724. __decorate([
  59725. BABYLON.serialize()
  59726. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  59727. return DefaultRenderingPipeline;
  59728. }(BABYLON.PostProcessRenderPipeline));
  59729. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  59730. })(BABYLON || (BABYLON = {}));
  59731. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  59732. var BABYLON;
  59733. (function (BABYLON) {
  59734. var GeometryBufferRenderer = /** @class */ (function () {
  59735. function GeometryBufferRenderer(scene, ratio) {
  59736. if (ratio === void 0) { ratio = 1; }
  59737. this._enablePosition = false;
  59738. this._scene = scene;
  59739. this._ratio = ratio;
  59740. // Render target
  59741. this._createRenderTargets();
  59742. }
  59743. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  59744. set: function (meshes) {
  59745. this._multiRenderTarget.renderList = meshes;
  59746. },
  59747. enumerable: true,
  59748. configurable: true
  59749. });
  59750. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  59751. get: function () {
  59752. return this._multiRenderTarget.isSupported;
  59753. },
  59754. enumerable: true,
  59755. configurable: true
  59756. });
  59757. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  59758. get: function () {
  59759. return this._enablePosition;
  59760. },
  59761. set: function (enable) {
  59762. this._enablePosition = enable;
  59763. this.dispose();
  59764. this._createRenderTargets();
  59765. },
  59766. enumerable: true,
  59767. configurable: true
  59768. });
  59769. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  59770. var material = subMesh.getMaterial();
  59771. if (material && material.disableDepthWrite) {
  59772. return false;
  59773. }
  59774. var defines = [];
  59775. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  59776. var mesh = subMesh.getMesh();
  59777. // Alpha test
  59778. if (material && material.needAlphaTesting()) {
  59779. defines.push("#define ALPHATEST");
  59780. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59781. attribs.push(BABYLON.VertexBuffer.UVKind);
  59782. defines.push("#define UV1");
  59783. }
  59784. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59785. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59786. defines.push("#define UV2");
  59787. }
  59788. }
  59789. // Buffers
  59790. if (this._enablePosition) {
  59791. defines.push("#define POSITION");
  59792. }
  59793. // Bones
  59794. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59795. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59796. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59797. if (mesh.numBoneInfluencers > 4) {
  59798. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59799. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59800. }
  59801. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59802. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  59803. }
  59804. else {
  59805. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59806. }
  59807. // Instances
  59808. if (useInstances) {
  59809. defines.push("#define INSTANCES");
  59810. attribs.push("world0");
  59811. attribs.push("world1");
  59812. attribs.push("world2");
  59813. attribs.push("world3");
  59814. }
  59815. // Get correct effect
  59816. var join = defines.join("\n");
  59817. if (this._cachedDefines !== join) {
  59818. this._cachedDefines = join;
  59819. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  59820. }
  59821. return this._effect.isReady();
  59822. };
  59823. GeometryBufferRenderer.prototype.getGBuffer = function () {
  59824. return this._multiRenderTarget;
  59825. };
  59826. // Methods
  59827. GeometryBufferRenderer.prototype.dispose = function () {
  59828. this.getGBuffer().dispose();
  59829. };
  59830. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  59831. var _this = this;
  59832. var engine = this._scene.getEngine();
  59833. var count = this._enablePosition ? 3 : 2;
  59834. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  59835. if (!this.isSupported) {
  59836. return;
  59837. }
  59838. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59839. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59840. this._multiRenderTarget.refreshRate = 1;
  59841. this._multiRenderTarget.renderParticles = false;
  59842. this._multiRenderTarget.renderList = null;
  59843. // set default depth value to 1.0 (far away)
  59844. this._multiRenderTarget.onClearObservable.add(function (engine) {
  59845. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  59846. });
  59847. // Custom render function
  59848. var renderSubMesh = function (subMesh) {
  59849. var mesh = subMesh.getRenderingMesh();
  59850. var scene = _this._scene;
  59851. var engine = scene.getEngine();
  59852. var material = subMesh.getMaterial();
  59853. if (!material) {
  59854. return;
  59855. }
  59856. // Culling
  59857. engine.setState(material.backFaceCulling);
  59858. // Managing instances
  59859. var batch = mesh._getInstancesRenderList(subMesh._id);
  59860. if (batch.mustReturn) {
  59861. return;
  59862. }
  59863. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  59864. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  59865. engine.enableEffect(_this._effect);
  59866. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  59867. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  59868. _this._effect.setMatrix("view", scene.getViewMatrix());
  59869. // Alpha test
  59870. if (material && material.needAlphaTesting()) {
  59871. var alphaTexture = material.getAlphaTestTexture();
  59872. if (alphaTexture) {
  59873. _this._effect.setTexture("diffuseSampler", alphaTexture);
  59874. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59875. }
  59876. }
  59877. // Bones
  59878. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59879. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59880. }
  59881. // Draw
  59882. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  59883. }
  59884. };
  59885. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59886. var index;
  59887. if (depthOnlySubMeshes.length) {
  59888. engine.setColorWrite(false);
  59889. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59890. renderSubMesh(depthOnlySubMeshes.data[index]);
  59891. }
  59892. engine.setColorWrite(true);
  59893. }
  59894. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59895. renderSubMesh(opaqueSubMeshes.data[index]);
  59896. }
  59897. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59898. renderSubMesh(alphaTestSubMeshes.data[index]);
  59899. }
  59900. };
  59901. };
  59902. return GeometryBufferRenderer;
  59903. }());
  59904. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  59905. })(BABYLON || (BABYLON = {}));
  59906. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  59907. var BABYLON;
  59908. (function (BABYLON) {
  59909. var RefractionPostProcess = /** @class */ (function (_super) {
  59910. __extends(RefractionPostProcess, _super);
  59911. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  59912. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  59913. _this.color = color;
  59914. _this.depth = depth;
  59915. _this.colorLevel = colorLevel;
  59916. _this.onActivateObservable.add(function (cam) {
  59917. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  59918. });
  59919. _this.onApplyObservable.add(function (effect) {
  59920. effect.setColor3("baseColor", _this.color);
  59921. effect.setFloat("depth", _this.depth);
  59922. effect.setFloat("colorLevel", _this.colorLevel);
  59923. effect.setTexture("refractionSampler", _this._refRexture);
  59924. });
  59925. return _this;
  59926. }
  59927. // Methods
  59928. RefractionPostProcess.prototype.dispose = function (camera) {
  59929. if (this._refRexture) {
  59930. this._refRexture.dispose();
  59931. }
  59932. _super.prototype.dispose.call(this, camera);
  59933. };
  59934. return RefractionPostProcess;
  59935. }(BABYLON.PostProcess));
  59936. BABYLON.RefractionPostProcess = RefractionPostProcess;
  59937. })(BABYLON || (BABYLON = {}));
  59938. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  59939. var BABYLON;
  59940. (function (BABYLON) {
  59941. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  59942. __extends(BlackAndWhitePostProcess, _super);
  59943. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  59944. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  59945. _this.degree = 1;
  59946. _this.onApplyObservable.add(function (effect) {
  59947. effect.setFloat("degree", _this.degree);
  59948. });
  59949. return _this;
  59950. }
  59951. return BlackAndWhitePostProcess;
  59952. }(BABYLON.PostProcess));
  59953. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  59954. })(BABYLON || (BABYLON = {}));
  59955. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  59956. var BABYLON;
  59957. (function (BABYLON) {
  59958. var ConvolutionPostProcess = /** @class */ (function (_super) {
  59959. __extends(ConvolutionPostProcess, _super);
  59960. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  59961. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  59962. _this.kernel = kernel;
  59963. _this.onApply = function (effect) {
  59964. effect.setFloat2("screenSize", _this.width, _this.height);
  59965. effect.setArray("kernel", _this.kernel);
  59966. };
  59967. return _this;
  59968. }
  59969. // Statics
  59970. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  59971. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  59972. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  59973. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  59974. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  59975. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  59976. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  59977. return ConvolutionPostProcess;
  59978. }(BABYLON.PostProcess));
  59979. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  59980. })(BABYLON || (BABYLON = {}));
  59981. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  59982. var BABYLON;
  59983. (function (BABYLON) {
  59984. var FilterPostProcess = /** @class */ (function (_super) {
  59985. __extends(FilterPostProcess, _super);
  59986. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  59987. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  59988. _this.kernelMatrix = kernelMatrix;
  59989. _this.onApply = function (effect) {
  59990. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  59991. };
  59992. return _this;
  59993. }
  59994. return FilterPostProcess;
  59995. }(BABYLON.PostProcess));
  59996. BABYLON.FilterPostProcess = FilterPostProcess;
  59997. })(BABYLON || (BABYLON = {}));
  59998. //# sourceMappingURL=babylon.filterPostProcess.js.map
  59999. var BABYLON;
  60000. (function (BABYLON) {
  60001. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  60002. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  60003. __extends(VolumetricLightScatteringPostProcess, _super);
  60004. /**
  60005. * @constructor
  60006. * @param {string} name - The post-process name
  60007. * @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)
  60008. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  60009. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  60010. * @param {number} samples - The post-process quality, default 100
  60011. * @param {number} samplingMode - The post-process filtering mode
  60012. * @param {BABYLON.Engine} engine - The babylon engine
  60013. * @param {boolean} reusable - If the post-process is reusable
  60014. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  60015. */
  60016. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  60017. if (samples === void 0) { samples = 100; }
  60018. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60019. 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;
  60020. _this._screenCoordinates = BABYLON.Vector2.Zero();
  60021. /**
  60022. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  60023. * @type {Vector3}
  60024. */
  60025. _this.customMeshPosition = BABYLON.Vector3.Zero();
  60026. /**
  60027. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  60028. * @type {boolean}
  60029. */
  60030. _this.useCustomMeshPosition = false;
  60031. /**
  60032. * If the post-process should inverse the light scattering direction
  60033. * @type {boolean}
  60034. */
  60035. _this.invert = true;
  60036. /**
  60037. * Array containing the excluded meshes not rendered in the internal pass
  60038. */
  60039. _this.excludedMeshes = new Array();
  60040. /**
  60041. * Controls the overall intensity of the post-process
  60042. * @type {number}
  60043. */
  60044. _this.exposure = 0.3;
  60045. /**
  60046. * Dissipates each sample's contribution in range [0, 1]
  60047. * @type {number}
  60048. */
  60049. _this.decay = 0.96815;
  60050. /**
  60051. * Controls the overall intensity of each sample
  60052. * @type {number}
  60053. */
  60054. _this.weight = 0.58767;
  60055. /**
  60056. * Controls the density of each sample
  60057. * @type {number}
  60058. */
  60059. _this.density = 0.926;
  60060. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  60061. engine = scene.getEngine();
  60062. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  60063. // Configure mesh
  60064. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  60065. // Configure
  60066. _this._createPass(scene, ratio.passRatio || ratio);
  60067. _this.onActivate = function (camera) {
  60068. if (!_this.isSupported) {
  60069. _this.dispose(camera);
  60070. }
  60071. _this.onActivate = null;
  60072. };
  60073. _this.onApplyObservable.add(function (effect) {
  60074. _this._updateMeshScreenCoordinates(scene);
  60075. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  60076. effect.setFloat("exposure", _this.exposure);
  60077. effect.setFloat("decay", _this.decay);
  60078. effect.setFloat("weight", _this.weight);
  60079. effect.setFloat("density", _this.density);
  60080. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  60081. });
  60082. return _this;
  60083. }
  60084. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  60085. get: function () {
  60086. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  60087. return false;
  60088. },
  60089. set: function (useDiffuseColor) {
  60090. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  60091. },
  60092. enumerable: true,
  60093. configurable: true
  60094. });
  60095. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  60096. return "VolumetricLightScatteringPostProcess";
  60097. };
  60098. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  60099. var mesh = subMesh.getMesh();
  60100. // Render this.mesh as default
  60101. if (mesh === this.mesh && mesh.material) {
  60102. return mesh.material.isReady(mesh);
  60103. }
  60104. var defines = [];
  60105. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60106. var material = subMesh.getMaterial();
  60107. // Alpha test
  60108. if (material) {
  60109. if (material.needAlphaTesting()) {
  60110. defines.push("#define ALPHATEST");
  60111. }
  60112. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60113. attribs.push(BABYLON.VertexBuffer.UVKind);
  60114. defines.push("#define UV1");
  60115. }
  60116. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60117. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60118. defines.push("#define UV2");
  60119. }
  60120. }
  60121. // Bones
  60122. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60123. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60124. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60125. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60126. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  60127. }
  60128. else {
  60129. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60130. }
  60131. // Instances
  60132. if (useInstances) {
  60133. defines.push("#define INSTANCES");
  60134. attribs.push("world0");
  60135. attribs.push("world1");
  60136. attribs.push("world2");
  60137. attribs.push("world3");
  60138. }
  60139. // Get correct effect
  60140. var join = defines.join("\n");
  60141. if (this._cachedDefines !== join) {
  60142. this._cachedDefines = join;
  60143. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  60144. }
  60145. return this._volumetricLightScatteringPass.isReady();
  60146. };
  60147. /**
  60148. * Sets the new light position for light scattering effect
  60149. * @param {BABYLON.Vector3} The new custom light position
  60150. */
  60151. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  60152. this.customMeshPosition = position;
  60153. };
  60154. /**
  60155. * Returns the light position for light scattering effect
  60156. * @return {BABYLON.Vector3} The custom light position
  60157. */
  60158. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  60159. return this.customMeshPosition;
  60160. };
  60161. /**
  60162. * Disposes the internal assets and detaches the post-process from the camera
  60163. */
  60164. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  60165. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  60166. if (rttIndex !== -1) {
  60167. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  60168. }
  60169. this._volumetricLightScatteringRTT.dispose();
  60170. _super.prototype.dispose.call(this, camera);
  60171. };
  60172. /**
  60173. * Returns the render target texture used by the post-process
  60174. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  60175. */
  60176. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  60177. return this._volumetricLightScatteringRTT;
  60178. };
  60179. // Private methods
  60180. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  60181. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  60182. return true;
  60183. }
  60184. return false;
  60185. };
  60186. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  60187. var _this = this;
  60188. var engine = scene.getEngine();
  60189. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  60190. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60191. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60192. this._volumetricLightScatteringRTT.renderList = null;
  60193. this._volumetricLightScatteringRTT.renderParticles = false;
  60194. var camera = this.getCamera();
  60195. if (camera) {
  60196. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  60197. }
  60198. else {
  60199. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  60200. }
  60201. // Custom render function for submeshes
  60202. var renderSubMesh = function (subMesh) {
  60203. var mesh = subMesh.getRenderingMesh();
  60204. if (_this._meshExcluded(mesh)) {
  60205. return;
  60206. }
  60207. var material = subMesh.getMaterial();
  60208. if (!material) {
  60209. return;
  60210. }
  60211. var scene = mesh.getScene();
  60212. var engine = scene.getEngine();
  60213. // Culling
  60214. engine.setState(material.backFaceCulling);
  60215. // Managing instances
  60216. var batch = mesh._getInstancesRenderList(subMesh._id);
  60217. if (batch.mustReturn) {
  60218. return;
  60219. }
  60220. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  60221. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  60222. var effect = _this._volumetricLightScatteringPass;
  60223. if (mesh === _this.mesh) {
  60224. if (subMesh.effect) {
  60225. effect = subMesh.effect;
  60226. }
  60227. else {
  60228. effect = material.getEffect();
  60229. }
  60230. }
  60231. engine.enableEffect(effect);
  60232. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  60233. if (mesh === _this.mesh) {
  60234. material.bind(mesh.getWorldMatrix(), mesh);
  60235. }
  60236. else {
  60237. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  60238. // Alpha test
  60239. if (material && material.needAlphaTesting()) {
  60240. var alphaTexture = material.getAlphaTestTexture();
  60241. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  60242. if (alphaTexture) {
  60243. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  60244. }
  60245. }
  60246. // Bones
  60247. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  60248. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  60249. }
  60250. }
  60251. // Draw
  60252. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  60253. }
  60254. };
  60255. // Render target texture callbacks
  60256. var savedSceneClearColor;
  60257. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  60258. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  60259. savedSceneClearColor = scene.clearColor;
  60260. scene.clearColor = sceneClearColor;
  60261. });
  60262. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  60263. scene.clearColor = savedSceneClearColor;
  60264. });
  60265. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  60266. var engine = scene.getEngine();
  60267. var index;
  60268. if (depthOnlySubMeshes.length) {
  60269. engine.setColorWrite(false);
  60270. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  60271. renderSubMesh(depthOnlySubMeshes.data[index]);
  60272. }
  60273. engine.setColorWrite(true);
  60274. }
  60275. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60276. renderSubMesh(opaqueSubMeshes.data[index]);
  60277. }
  60278. engine.setAlphaTesting(true);
  60279. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60280. renderSubMesh(alphaTestSubMeshes.data[index]);
  60281. }
  60282. engine.setAlphaTesting(false);
  60283. if (transparentSubMeshes.length) {
  60284. // Sort sub meshes
  60285. for (index = 0; index < transparentSubMeshes.length; index++) {
  60286. var submesh = transparentSubMeshes.data[index];
  60287. var boundingInfo = submesh.getBoundingInfo();
  60288. if (boundingInfo && scene.activeCamera) {
  60289. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  60290. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  60291. }
  60292. }
  60293. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  60294. sortedArray.sort(function (a, b) {
  60295. // Alpha index first
  60296. if (a._alphaIndex > b._alphaIndex) {
  60297. return 1;
  60298. }
  60299. if (a._alphaIndex < b._alphaIndex) {
  60300. return -1;
  60301. }
  60302. // Then distance to camera
  60303. if (a._distanceToCamera < b._distanceToCamera) {
  60304. return 1;
  60305. }
  60306. if (a._distanceToCamera > b._distanceToCamera) {
  60307. return -1;
  60308. }
  60309. return 0;
  60310. });
  60311. // Render sub meshes
  60312. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  60313. for (index = 0; index < sortedArray.length; index++) {
  60314. renderSubMesh(sortedArray[index]);
  60315. }
  60316. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  60317. }
  60318. };
  60319. };
  60320. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  60321. var transform = scene.getTransformMatrix();
  60322. var meshPosition;
  60323. if (this.useCustomMeshPosition) {
  60324. meshPosition = this.customMeshPosition;
  60325. }
  60326. else if (this.attachedNode) {
  60327. meshPosition = this.attachedNode.position;
  60328. }
  60329. else {
  60330. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  60331. }
  60332. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  60333. this._screenCoordinates.x = pos.x / this._viewPort.width;
  60334. this._screenCoordinates.y = pos.y / this._viewPort.height;
  60335. if (this.invert)
  60336. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  60337. };
  60338. // Static methods
  60339. /**
  60340. * Creates a default mesh for the Volumeric Light Scattering post-process
  60341. * @param {string} The mesh name
  60342. * @param {BABYLON.Scene} The scene where to create the mesh
  60343. * @return {BABYLON.Mesh} the default mesh
  60344. */
  60345. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  60346. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  60347. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  60348. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  60349. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  60350. mesh.material = material;
  60351. return mesh;
  60352. };
  60353. __decorate([
  60354. BABYLON.serializeAsVector3()
  60355. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  60356. __decorate([
  60357. BABYLON.serialize()
  60358. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  60359. __decorate([
  60360. BABYLON.serialize()
  60361. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  60362. __decorate([
  60363. BABYLON.serializeAsMeshReference()
  60364. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  60365. __decorate([
  60366. BABYLON.serialize()
  60367. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  60368. __decorate([
  60369. BABYLON.serialize()
  60370. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  60371. __decorate([
  60372. BABYLON.serialize()
  60373. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  60374. __decorate([
  60375. BABYLON.serialize()
  60376. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  60377. __decorate([
  60378. BABYLON.serialize()
  60379. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  60380. return VolumetricLightScatteringPostProcess;
  60381. }(BABYLON.PostProcess));
  60382. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  60383. })(BABYLON || (BABYLON = {}));
  60384. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  60385. //
  60386. // This post-process allows the modification of rendered colors by using
  60387. // a 'look-up table' (LUT). This effect is also called Color Grading.
  60388. //
  60389. // The object needs to be provided an url to a texture containing the color
  60390. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  60391. // Use an image editing software to tweak the LUT to match your needs.
  60392. //
  60393. // For an example of a color LUT, see here:
  60394. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  60395. // For explanations on color grading, see here:
  60396. // http://udn.epicgames.com/Three/ColorGrading.html
  60397. //
  60398. var BABYLON;
  60399. (function (BABYLON) {
  60400. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  60401. __extends(ColorCorrectionPostProcess, _super);
  60402. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  60403. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  60404. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  60405. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  60406. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60407. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60408. _this.onApply = function (effect) {
  60409. effect.setTexture("colorTable", _this._colorTableTexture);
  60410. };
  60411. return _this;
  60412. }
  60413. return ColorCorrectionPostProcess;
  60414. }(BABYLON.PostProcess));
  60415. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  60416. })(BABYLON || (BABYLON = {}));
  60417. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  60418. var BABYLON;
  60419. (function (BABYLON) {
  60420. var TonemappingOperator;
  60421. (function (TonemappingOperator) {
  60422. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  60423. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  60424. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  60425. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  60426. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  60427. ;
  60428. var TonemapPostProcess = /** @class */ (function (_super) {
  60429. __extends(TonemapPostProcess, _super);
  60430. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  60431. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60432. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60433. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  60434. _this._operator = _operator;
  60435. _this.exposureAdjustment = exposureAdjustment;
  60436. var defines = "#define ";
  60437. if (_this._operator === TonemappingOperator.Hable)
  60438. defines += "HABLE_TONEMAPPING";
  60439. else if (_this._operator === TonemappingOperator.Reinhard)
  60440. defines += "REINHARD_TONEMAPPING";
  60441. else if (_this._operator === TonemappingOperator.HejiDawson)
  60442. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  60443. else if (_this._operator === TonemappingOperator.Photographic)
  60444. defines += "PHOTOGRAPHIC_TONEMAPPING";
  60445. //sadly a second call to create the effect.
  60446. _this.updateEffect(defines);
  60447. _this.onApply = function (effect) {
  60448. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  60449. };
  60450. return _this;
  60451. }
  60452. return TonemapPostProcess;
  60453. }(BABYLON.PostProcess));
  60454. BABYLON.TonemapPostProcess = TonemapPostProcess;
  60455. })(BABYLON || (BABYLON = {}));
  60456. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  60457. var BABYLON;
  60458. (function (BABYLON) {
  60459. var DisplayPassPostProcess = /** @class */ (function (_super) {
  60460. __extends(DisplayPassPostProcess, _super);
  60461. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  60462. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  60463. }
  60464. return DisplayPassPostProcess;
  60465. }(BABYLON.PostProcess));
  60466. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  60467. })(BABYLON || (BABYLON = {}));
  60468. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  60469. var BABYLON;
  60470. (function (BABYLON) {
  60471. var HighlightsPostProcess = /** @class */ (function (_super) {
  60472. __extends(HighlightsPostProcess, _super);
  60473. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  60474. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60475. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  60476. }
  60477. return HighlightsPostProcess;
  60478. }(BABYLON.PostProcess));
  60479. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  60480. })(BABYLON || (BABYLON = {}));
  60481. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  60482. var BABYLON;
  60483. (function (BABYLON) {
  60484. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  60485. __extends(ImageProcessingPostProcess, _super);
  60486. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  60487. if (camera === void 0) { camera = null; }
  60488. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60489. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  60490. _this._fromLinearSpace = true;
  60491. /**
  60492. * Defines cache preventing GC.
  60493. */
  60494. _this._defines = {
  60495. IMAGEPROCESSING: false,
  60496. VIGNETTE: false,
  60497. VIGNETTEBLENDMODEMULTIPLY: false,
  60498. VIGNETTEBLENDMODEOPAQUE: false,
  60499. TONEMAPPING: false,
  60500. CONTRAST: false,
  60501. COLORCURVES: false,
  60502. COLORGRADING: false,
  60503. COLORGRADING3D: false,
  60504. FROMLINEARSPACE: false,
  60505. SAMPLER3DGREENDEPTH: false,
  60506. SAMPLER3DBGRMAP: false,
  60507. IMAGEPROCESSINGPOSTPROCESS: false,
  60508. EXPOSURE: false,
  60509. };
  60510. // Setup the default processing configuration to the scene.
  60511. _this._attachImageProcessingConfiguration(null, true);
  60512. _this.imageProcessingConfiguration.applyByPostProcess = true;
  60513. _this.onApply = function (effect) {
  60514. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  60515. };
  60516. return _this;
  60517. }
  60518. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  60519. /**
  60520. * Gets the image processing configuration used either in this material.
  60521. */
  60522. get: function () {
  60523. return this._imageProcessingConfiguration;
  60524. },
  60525. /**
  60526. * Sets the Default image processing configuration used either in the this material.
  60527. *
  60528. * If sets to null, the scene one is in use.
  60529. */
  60530. set: function (value) {
  60531. this._attachImageProcessingConfiguration(value);
  60532. },
  60533. enumerable: true,
  60534. configurable: true
  60535. });
  60536. /**
  60537. * Attaches a new image processing configuration to the PBR Material.
  60538. * @param configuration
  60539. */
  60540. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  60541. var _this = this;
  60542. if (doNotBuild === void 0) { doNotBuild = false; }
  60543. if (configuration === this._imageProcessingConfiguration) {
  60544. return;
  60545. }
  60546. // Detaches observer.
  60547. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  60548. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  60549. }
  60550. // Pick the scene configuration if needed.
  60551. if (!configuration) {
  60552. var scene = null;
  60553. var engine = this.getEngine();
  60554. var camera = this.getCamera();
  60555. if (camera) {
  60556. scene = camera.getScene();
  60557. }
  60558. else if (engine && engine.scenes) {
  60559. var scenes = engine.scenes;
  60560. scene = scenes[scenes.length - 1];
  60561. }
  60562. else {
  60563. scene = BABYLON.Engine.LastCreatedScene;
  60564. }
  60565. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  60566. }
  60567. else {
  60568. this._imageProcessingConfiguration = configuration;
  60569. }
  60570. // Attaches observer.
  60571. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  60572. _this._updateParameters();
  60573. });
  60574. // Ensure the effect will be rebuilt.
  60575. if (!doNotBuild) {
  60576. this._updateParameters();
  60577. }
  60578. };
  60579. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  60580. /**
  60581. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  60582. */
  60583. get: function () {
  60584. return this.imageProcessingConfiguration.colorCurves;
  60585. },
  60586. /**
  60587. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  60588. */
  60589. set: function (value) {
  60590. this.imageProcessingConfiguration.colorCurves = value;
  60591. },
  60592. enumerable: true,
  60593. configurable: true
  60594. });
  60595. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  60596. /**
  60597. * Gets wether the color curves effect is enabled.
  60598. */
  60599. get: function () {
  60600. return this.imageProcessingConfiguration.colorCurvesEnabled;
  60601. },
  60602. /**
  60603. * Sets wether the color curves effect is enabled.
  60604. */
  60605. set: function (value) {
  60606. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  60607. },
  60608. enumerable: true,
  60609. configurable: true
  60610. });
  60611. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  60612. /**
  60613. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  60614. */
  60615. get: function () {
  60616. return this.imageProcessingConfiguration.colorGradingTexture;
  60617. },
  60618. /**
  60619. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  60620. */
  60621. set: function (value) {
  60622. this.imageProcessingConfiguration.colorGradingTexture = value;
  60623. },
  60624. enumerable: true,
  60625. configurable: true
  60626. });
  60627. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  60628. /**
  60629. * Gets wether the color grading effect is enabled.
  60630. */
  60631. get: function () {
  60632. return this.imageProcessingConfiguration.colorGradingEnabled;
  60633. },
  60634. /**
  60635. * Gets wether the color grading effect is enabled.
  60636. */
  60637. set: function (value) {
  60638. this.imageProcessingConfiguration.colorGradingEnabled = value;
  60639. },
  60640. enumerable: true,
  60641. configurable: true
  60642. });
  60643. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  60644. /**
  60645. * Gets exposure used in the effect.
  60646. */
  60647. get: function () {
  60648. return this.imageProcessingConfiguration.exposure;
  60649. },
  60650. /**
  60651. * Sets exposure used in the effect.
  60652. */
  60653. set: function (value) {
  60654. this.imageProcessingConfiguration.exposure = value;
  60655. },
  60656. enumerable: true,
  60657. configurable: true
  60658. });
  60659. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  60660. /**
  60661. * Gets wether tonemapping is enabled or not.
  60662. */
  60663. get: function () {
  60664. return this._imageProcessingConfiguration.toneMappingEnabled;
  60665. },
  60666. /**
  60667. * Sets wether tonemapping is enabled or not
  60668. */
  60669. set: function (value) {
  60670. this._imageProcessingConfiguration.toneMappingEnabled = value;
  60671. },
  60672. enumerable: true,
  60673. configurable: true
  60674. });
  60675. ;
  60676. ;
  60677. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  60678. /**
  60679. * Gets contrast used in the effect.
  60680. */
  60681. get: function () {
  60682. return this.imageProcessingConfiguration.contrast;
  60683. },
  60684. /**
  60685. * Sets contrast used in the effect.
  60686. */
  60687. set: function (value) {
  60688. this.imageProcessingConfiguration.contrast = value;
  60689. },
  60690. enumerable: true,
  60691. configurable: true
  60692. });
  60693. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  60694. /**
  60695. * Gets Vignette stretch size.
  60696. */
  60697. get: function () {
  60698. return this.imageProcessingConfiguration.vignetteStretch;
  60699. },
  60700. /**
  60701. * Sets Vignette stretch size.
  60702. */
  60703. set: function (value) {
  60704. this.imageProcessingConfiguration.vignetteStretch = value;
  60705. },
  60706. enumerable: true,
  60707. configurable: true
  60708. });
  60709. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  60710. /**
  60711. * Gets Vignette centre X Offset.
  60712. */
  60713. get: function () {
  60714. return this.imageProcessingConfiguration.vignetteCentreX;
  60715. },
  60716. /**
  60717. * Sets Vignette centre X Offset.
  60718. */
  60719. set: function (value) {
  60720. this.imageProcessingConfiguration.vignetteCentreX = value;
  60721. },
  60722. enumerable: true,
  60723. configurable: true
  60724. });
  60725. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  60726. /**
  60727. * Gets Vignette centre Y Offset.
  60728. */
  60729. get: function () {
  60730. return this.imageProcessingConfiguration.vignetteCentreY;
  60731. },
  60732. /**
  60733. * Sets Vignette centre Y Offset.
  60734. */
  60735. set: function (value) {
  60736. this.imageProcessingConfiguration.vignetteCentreY = value;
  60737. },
  60738. enumerable: true,
  60739. configurable: true
  60740. });
  60741. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  60742. /**
  60743. * Gets Vignette weight or intensity of the vignette effect.
  60744. */
  60745. get: function () {
  60746. return this.imageProcessingConfiguration.vignetteWeight;
  60747. },
  60748. /**
  60749. * Sets Vignette weight or intensity of the vignette effect.
  60750. */
  60751. set: function (value) {
  60752. this.imageProcessingConfiguration.vignetteWeight = value;
  60753. },
  60754. enumerable: true,
  60755. configurable: true
  60756. });
  60757. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  60758. /**
  60759. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  60760. * if vignetteEnabled is set to true.
  60761. */
  60762. get: function () {
  60763. return this.imageProcessingConfiguration.vignetteColor;
  60764. },
  60765. /**
  60766. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  60767. * if vignetteEnabled is set to true.
  60768. */
  60769. set: function (value) {
  60770. this.imageProcessingConfiguration.vignetteColor = value;
  60771. },
  60772. enumerable: true,
  60773. configurable: true
  60774. });
  60775. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  60776. /**
  60777. * Gets Camera field of view used by the Vignette effect.
  60778. */
  60779. get: function () {
  60780. return this.imageProcessingConfiguration.vignetteCameraFov;
  60781. },
  60782. /**
  60783. * Sets Camera field of view used by the Vignette effect.
  60784. */
  60785. set: function (value) {
  60786. this.imageProcessingConfiguration.vignetteCameraFov = value;
  60787. },
  60788. enumerable: true,
  60789. configurable: true
  60790. });
  60791. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  60792. /**
  60793. * Gets the vignette blend mode allowing different kind of effect.
  60794. */
  60795. get: function () {
  60796. return this.imageProcessingConfiguration.vignetteBlendMode;
  60797. },
  60798. /**
  60799. * Sets the vignette blend mode allowing different kind of effect.
  60800. */
  60801. set: function (value) {
  60802. this.imageProcessingConfiguration.vignetteBlendMode = value;
  60803. },
  60804. enumerable: true,
  60805. configurable: true
  60806. });
  60807. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  60808. /**
  60809. * Gets wether the vignette effect is enabled.
  60810. */
  60811. get: function () {
  60812. return this.imageProcessingConfiguration.vignetteEnabled;
  60813. },
  60814. /**
  60815. * Sets wether the vignette effect is enabled.
  60816. */
  60817. set: function (value) {
  60818. this.imageProcessingConfiguration.vignetteEnabled = value;
  60819. },
  60820. enumerable: true,
  60821. configurable: true
  60822. });
  60823. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  60824. /**
  60825. * Gets wether the input of the processing is in Gamma or Linear Space.
  60826. */
  60827. get: function () {
  60828. return this._fromLinearSpace;
  60829. },
  60830. /**
  60831. * Sets wether the input of the processing is in Gamma or Linear Space.
  60832. */
  60833. set: function (value) {
  60834. if (this._fromLinearSpace === value) {
  60835. return;
  60836. }
  60837. this._fromLinearSpace = value;
  60838. this._updateParameters();
  60839. },
  60840. enumerable: true,
  60841. configurable: true
  60842. });
  60843. ImageProcessingPostProcess.prototype.getClassName = function () {
  60844. return "ImageProcessingPostProcess";
  60845. };
  60846. ImageProcessingPostProcess.prototype._updateParameters = function () {
  60847. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  60848. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  60849. var defines = "";
  60850. for (var define in this._defines) {
  60851. if (this._defines[define]) {
  60852. defines += "#define " + define + ";\r\n";
  60853. }
  60854. }
  60855. var samplers = ["textureSampler"];
  60856. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  60857. var uniforms = ["scale"];
  60858. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  60859. this.updateEffect(defines, uniforms, samplers);
  60860. };
  60861. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  60862. _super.prototype.dispose.call(this, camera);
  60863. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  60864. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  60865. }
  60866. this.imageProcessingConfiguration.applyByPostProcess = false;
  60867. };
  60868. __decorate([
  60869. BABYLON.serialize()
  60870. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  60871. return ImageProcessingPostProcess;
  60872. }(BABYLON.PostProcess));
  60873. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  60874. })(BABYLON || (BABYLON = {}));
  60875. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  60876. var BABYLON;
  60877. (function (BABYLON) {
  60878. var BlurPostProcess = /** @class */ (function (_super) {
  60879. __extends(BlurPostProcess, _super);
  60880. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  60881. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60882. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60883. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  60884. _this.direction = direction;
  60885. _this._packedFloat = false;
  60886. _this.onApplyObservable.add(function (effect) {
  60887. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  60888. });
  60889. _this.kernel = kernel;
  60890. return _this;
  60891. }
  60892. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  60893. /**
  60894. * Gets the length in pixels of the blur sample region
  60895. */
  60896. get: function () {
  60897. return this._idealKernel;
  60898. },
  60899. /**
  60900. * Sets the length in pixels of the blur sample region
  60901. */
  60902. set: function (v) {
  60903. if (this._idealKernel === v) {
  60904. return;
  60905. }
  60906. v = Math.max(v, 1);
  60907. this._idealKernel = v;
  60908. this._kernel = this._nearestBestKernel(v);
  60909. this._updateParameters();
  60910. },
  60911. enumerable: true,
  60912. configurable: true
  60913. });
  60914. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  60915. /**
  60916. * Gets wether or not the blur is unpacking/repacking floats
  60917. */
  60918. get: function () {
  60919. return this._packedFloat;
  60920. },
  60921. /**
  60922. * Sets wether or not the blur needs to unpack/repack floats
  60923. */
  60924. set: function (v) {
  60925. if (this._packedFloat === v) {
  60926. return;
  60927. }
  60928. this._packedFloat = v;
  60929. this._updateParameters();
  60930. },
  60931. enumerable: true,
  60932. configurable: true
  60933. });
  60934. BlurPostProcess.prototype._updateParameters = function () {
  60935. // Generate sampling offsets and weights
  60936. var N = this._kernel;
  60937. var centerIndex = (N - 1) / 2;
  60938. // Generate Gaussian sampling weights over kernel
  60939. var offsets = [];
  60940. var weights = [];
  60941. var totalWeight = 0;
  60942. for (var i = 0; i < N; i++) {
  60943. var u = i / (N - 1);
  60944. var w = this._gaussianWeight(u * 2.0 - 1);
  60945. offsets[i] = (i - centerIndex);
  60946. weights[i] = w;
  60947. totalWeight += w;
  60948. }
  60949. // Normalize weights
  60950. for (var i = 0; i < weights.length; i++) {
  60951. weights[i] /= totalWeight;
  60952. }
  60953. // Optimize: combine samples to take advantage of hardware linear sampling
  60954. // Walk from left to center, combining pairs (symmetrically)
  60955. var linearSamplingWeights = [];
  60956. var linearSamplingOffsets = [];
  60957. var linearSamplingMap = [];
  60958. for (var i = 0; i <= centerIndex; i += 2) {
  60959. var j = Math.min(i + 1, Math.floor(centerIndex));
  60960. var singleCenterSample = i === j;
  60961. if (singleCenterSample) {
  60962. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  60963. }
  60964. else {
  60965. var sharedCell = j === centerIndex;
  60966. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  60967. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  60968. if (offsetLinear === 0) {
  60969. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  60970. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  60971. }
  60972. else {
  60973. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  60974. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  60975. }
  60976. }
  60977. }
  60978. for (var i = 0; i < linearSamplingMap.length; i++) {
  60979. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  60980. linearSamplingWeights[i] = linearSamplingMap[i].w;
  60981. }
  60982. // Replace with optimized
  60983. offsets = linearSamplingOffsets;
  60984. weights = linearSamplingWeights;
  60985. // Generate shaders
  60986. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  60987. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  60988. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  60989. var defines = "";
  60990. for (var i = 0; i < varyingCount; i++) {
  60991. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  60992. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  60993. }
  60994. var depCount = 0;
  60995. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  60996. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  60997. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  60998. depCount++;
  60999. }
  61000. if (this.packedFloat) {
  61001. defines += "#define PACKEDFLOAT 1";
  61002. }
  61003. this.updateEffect(defines, null, null, {
  61004. varyingCount: varyingCount,
  61005. depCount: depCount
  61006. });
  61007. };
  61008. /**
  61009. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  61010. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  61011. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  61012. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  61013. * The gaps between physical kernels are compensated for in the weighting of the samples
  61014. * @param idealKernel Ideal blur kernel.
  61015. * @return Nearest best kernel.
  61016. */
  61017. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  61018. var v = Math.round(idealKernel);
  61019. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  61020. var k = _a[_i];
  61021. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  61022. return Math.max(k, 3);
  61023. }
  61024. }
  61025. return Math.max(v, 3);
  61026. };
  61027. /**
  61028. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  61029. * @param x The point on the Gaussian distribution to sample.
  61030. * @return the value of the Gaussian function at x.
  61031. */
  61032. BlurPostProcess.prototype._gaussianWeight = function (x) {
  61033. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  61034. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  61035. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  61036. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  61037. // truncated at around 1.3% of peak strength.
  61038. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  61039. var sigma = (1 / 3);
  61040. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  61041. var exponent = -((x * x) / (2.0 * sigma * sigma));
  61042. var weight = (1.0 / denominator) * Math.exp(exponent);
  61043. return weight;
  61044. };
  61045. /**
  61046. * Generates a string that can be used as a floating point number in GLSL.
  61047. * @param x Value to print.
  61048. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  61049. * @return GLSL float string.
  61050. */
  61051. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  61052. if (decimalFigures === void 0) { decimalFigures = 8; }
  61053. return x.toFixed(decimalFigures).replace(/0+$/, '');
  61054. };
  61055. return BlurPostProcess;
  61056. }(BABYLON.PostProcess));
  61057. BABYLON.BlurPostProcess = BlurPostProcess;
  61058. })(BABYLON || (BABYLON = {}));
  61059. //# sourceMappingURL=babylon.blurPostProcess.js.map
  61060. var BABYLON;
  61061. (function (BABYLON) {
  61062. var Bone = /** @class */ (function (_super) {
  61063. __extends(Bone, _super);
  61064. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  61065. if (parentBone === void 0) { parentBone = null; }
  61066. if (localMatrix === void 0) { localMatrix = null; }
  61067. if (restPose === void 0) { restPose = null; }
  61068. if (baseMatrix === void 0) { baseMatrix = null; }
  61069. if (index === void 0) { index = null; }
  61070. var _this = _super.call(this, name, skeleton.getScene()) || this;
  61071. _this.name = name;
  61072. _this.children = new Array();
  61073. _this.animations = new Array();
  61074. // Set this value to map this bone to a different index in the transform matrices.
  61075. // Set this value to -1 to exclude the bone from the transform matrices.
  61076. _this._index = null;
  61077. _this._worldTransform = new BABYLON.Matrix();
  61078. _this._absoluteTransform = new BABYLON.Matrix();
  61079. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  61080. _this._scaleMatrix = BABYLON.Matrix.Identity();
  61081. _this._scaleVector = BABYLON.Vector3.One();
  61082. _this._negateScaleChildren = BABYLON.Vector3.One();
  61083. _this._scalingDeterminant = 1;
  61084. _this._skeleton = skeleton;
  61085. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  61086. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  61087. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  61088. _this._index = index;
  61089. skeleton.bones.push(_this);
  61090. _this.setParent(parentBone, false);
  61091. _this._updateDifferenceMatrix();
  61092. return _this;
  61093. }
  61094. Object.defineProperty(Bone.prototype, "_matrix", {
  61095. get: function () {
  61096. return this._localMatrix;
  61097. },
  61098. set: function (val) {
  61099. if (this._localMatrix) {
  61100. this._localMatrix.copyFrom(val);
  61101. }
  61102. else {
  61103. this._localMatrix = val;
  61104. }
  61105. },
  61106. enumerable: true,
  61107. configurable: true
  61108. });
  61109. // Members
  61110. Bone.prototype.getSkeleton = function () {
  61111. return this._skeleton;
  61112. };
  61113. Bone.prototype.getParent = function () {
  61114. return this._parent;
  61115. };
  61116. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  61117. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  61118. if (this._parent === parent) {
  61119. return;
  61120. }
  61121. if (this._parent) {
  61122. var index = this._parent.children.indexOf(this);
  61123. if (index !== -1) {
  61124. this._parent.children.splice(index, 1);
  61125. }
  61126. }
  61127. this._parent = parent;
  61128. if (this._parent) {
  61129. this._parent.children.push(this);
  61130. }
  61131. if (updateDifferenceMatrix) {
  61132. this._updateDifferenceMatrix();
  61133. }
  61134. };
  61135. Bone.prototype.getLocalMatrix = function () {
  61136. return this._localMatrix;
  61137. };
  61138. Bone.prototype.getBaseMatrix = function () {
  61139. return this._baseMatrix;
  61140. };
  61141. Bone.prototype.getRestPose = function () {
  61142. return this._restPose;
  61143. };
  61144. Bone.prototype.returnToRest = function () {
  61145. this.updateMatrix(this._restPose.clone());
  61146. };
  61147. Bone.prototype.getWorldMatrix = function () {
  61148. return this._worldTransform;
  61149. };
  61150. Bone.prototype.getInvertedAbsoluteTransform = function () {
  61151. return this._invertedAbsoluteTransform;
  61152. };
  61153. Bone.prototype.getAbsoluteTransform = function () {
  61154. return this._absoluteTransform;
  61155. };
  61156. Object.defineProperty(Bone.prototype, "position", {
  61157. // Properties (matches AbstractMesh properties)
  61158. get: function () {
  61159. return this.getPosition();
  61160. },
  61161. set: function (newPosition) {
  61162. this.setPosition(newPosition);
  61163. },
  61164. enumerable: true,
  61165. configurable: true
  61166. });
  61167. Object.defineProperty(Bone.prototype, "rotation", {
  61168. get: function () {
  61169. return this.getRotation();
  61170. },
  61171. set: function (newRotation) {
  61172. this.setRotation(newRotation);
  61173. },
  61174. enumerable: true,
  61175. configurable: true
  61176. });
  61177. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  61178. get: function () {
  61179. return this.getRotationQuaternion();
  61180. },
  61181. set: function (newRotation) {
  61182. this.setRotationQuaternion(newRotation);
  61183. },
  61184. enumerable: true,
  61185. configurable: true
  61186. });
  61187. Object.defineProperty(Bone.prototype, "scaling", {
  61188. get: function () {
  61189. return this.getScale();
  61190. },
  61191. set: function (newScaling) {
  61192. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  61193. },
  61194. enumerable: true,
  61195. configurable: true
  61196. });
  61197. // Methods
  61198. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  61199. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  61200. this._baseMatrix = matrix.clone();
  61201. this._localMatrix = matrix.clone();
  61202. this._skeleton._markAsDirty();
  61203. if (updateDifferenceMatrix) {
  61204. this._updateDifferenceMatrix();
  61205. }
  61206. };
  61207. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  61208. if (!rootMatrix) {
  61209. rootMatrix = this._baseMatrix;
  61210. }
  61211. if (this._parent) {
  61212. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  61213. }
  61214. else {
  61215. this._absoluteTransform.copyFrom(rootMatrix);
  61216. }
  61217. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  61218. for (var index = 0; index < this.children.length; index++) {
  61219. this.children[index]._updateDifferenceMatrix();
  61220. }
  61221. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  61222. };
  61223. Bone.prototype.markAsDirty = function () {
  61224. this._currentRenderId++;
  61225. this._skeleton._markAsDirty();
  61226. };
  61227. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  61228. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  61229. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  61230. // all animation may be coming from a library skeleton, so may need to create animation
  61231. if (this.animations.length === 0) {
  61232. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  61233. this.animations[0].setKeys([]);
  61234. }
  61235. // get animation info / verify there is such a range from the source bone
  61236. var sourceRange = source.animations[0].getRange(rangeName);
  61237. if (!sourceRange) {
  61238. return false;
  61239. }
  61240. var from = sourceRange.from;
  61241. var to = sourceRange.to;
  61242. var sourceKeys = source.animations[0].getKeys();
  61243. // rescaling prep
  61244. var sourceBoneLength = source.length;
  61245. var sourceParent = source.getParent();
  61246. var parent = this.getParent();
  61247. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  61248. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  61249. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  61250. var destKeys = this.animations[0].getKeys();
  61251. // loop vars declaration
  61252. var orig;
  61253. var origTranslation;
  61254. var mat;
  61255. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  61256. orig = sourceKeys[key];
  61257. if (orig.frame >= from && orig.frame <= to) {
  61258. if (rescaleAsRequired) {
  61259. mat = orig.value.clone();
  61260. // scale based on parent ratio, when bone has parent
  61261. if (parentScalingReqd) {
  61262. origTranslation = mat.getTranslation();
  61263. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  61264. // scale based on skeleton dimension ratio when root bone, and value is passed
  61265. }
  61266. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  61267. origTranslation = mat.getTranslation();
  61268. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  61269. // use original when root bone, and no data for skelDimensionsRatio
  61270. }
  61271. else {
  61272. mat = orig.value;
  61273. }
  61274. }
  61275. else {
  61276. mat = orig.value;
  61277. }
  61278. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  61279. }
  61280. }
  61281. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  61282. return true;
  61283. };
  61284. /**
  61285. * Translate the bone in local or world space.
  61286. * @param vec The amount to translate the bone.
  61287. * @param space The space that the translation is in.
  61288. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61289. */
  61290. Bone.prototype.translate = function (vec, space, mesh) {
  61291. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61292. var lm = this.getLocalMatrix();
  61293. if (space == BABYLON.Space.LOCAL) {
  61294. lm.m[12] += vec.x;
  61295. lm.m[13] += vec.y;
  61296. lm.m[14] += vec.z;
  61297. }
  61298. else {
  61299. var wm = null;
  61300. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61301. if (mesh) {
  61302. wm = mesh.getWorldMatrix();
  61303. }
  61304. this._skeleton.computeAbsoluteTransforms();
  61305. var tmat = Bone._tmpMats[0];
  61306. var tvec = Bone._tmpVecs[0];
  61307. if (this._parent) {
  61308. if (mesh && wm) {
  61309. tmat.copyFrom(this._parent.getAbsoluteTransform());
  61310. tmat.multiplyToRef(wm, tmat);
  61311. }
  61312. else {
  61313. tmat.copyFrom(this._parent.getAbsoluteTransform());
  61314. }
  61315. }
  61316. tmat.m[12] = 0;
  61317. tmat.m[13] = 0;
  61318. tmat.m[14] = 0;
  61319. tmat.invert();
  61320. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  61321. lm.m[12] += tvec.x;
  61322. lm.m[13] += tvec.y;
  61323. lm.m[14] += tvec.z;
  61324. }
  61325. this.markAsDirty();
  61326. };
  61327. /**
  61328. * Set the postion of the bone in local or world space.
  61329. * @param position The position to set the bone.
  61330. * @param space The space that the position is in.
  61331. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61332. */
  61333. Bone.prototype.setPosition = function (position, space, mesh) {
  61334. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61335. var lm = this.getLocalMatrix();
  61336. if (space == BABYLON.Space.LOCAL) {
  61337. lm.m[12] = position.x;
  61338. lm.m[13] = position.y;
  61339. lm.m[14] = position.z;
  61340. }
  61341. else {
  61342. var wm = null;
  61343. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61344. if (mesh) {
  61345. wm = mesh.getWorldMatrix();
  61346. }
  61347. this._skeleton.computeAbsoluteTransforms();
  61348. var tmat = Bone._tmpMats[0];
  61349. var vec = Bone._tmpVecs[0];
  61350. if (this._parent) {
  61351. if (mesh && wm) {
  61352. tmat.copyFrom(this._parent.getAbsoluteTransform());
  61353. tmat.multiplyToRef(wm, tmat);
  61354. }
  61355. else {
  61356. tmat.copyFrom(this._parent.getAbsoluteTransform());
  61357. }
  61358. }
  61359. tmat.invert();
  61360. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  61361. lm.m[12] = vec.x;
  61362. lm.m[13] = vec.y;
  61363. lm.m[14] = vec.z;
  61364. }
  61365. this.markAsDirty();
  61366. };
  61367. /**
  61368. * Set the absolute postion of the bone (world space).
  61369. * @param position The position to set the bone.
  61370. * @param mesh The mesh that this bone is attached to.
  61371. */
  61372. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  61373. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  61374. };
  61375. /**
  61376. * Set the scale of the bone on the x, y and z axes.
  61377. * @param x The scale of the bone on the x axis.
  61378. * @param x The scale of the bone on the y axis.
  61379. * @param z The scale of the bone on the z axis.
  61380. * @param scaleChildren Set this to true if children of the bone should be scaled.
  61381. */
  61382. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  61383. if (scaleChildren === void 0) { scaleChildren = false; }
  61384. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  61385. if (!scaleChildren) {
  61386. this._negateScaleChildren.x = 1 / x;
  61387. this._negateScaleChildren.y = 1 / y;
  61388. this._negateScaleChildren.z = 1 / z;
  61389. }
  61390. this._syncScaleVector();
  61391. }
  61392. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  61393. };
  61394. /**
  61395. * Scale the bone on the x, y and z axes.
  61396. * @param x The amount to scale the bone on the x axis.
  61397. * @param x The amount to scale the bone on the y axis.
  61398. * @param z The amount to scale the bone on the z axis.
  61399. * @param scaleChildren Set this to true if children of the bone should be scaled.
  61400. */
  61401. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  61402. if (scaleChildren === void 0) { scaleChildren = false; }
  61403. var locMat = this.getLocalMatrix();
  61404. var origLocMat = Bone._tmpMats[0];
  61405. origLocMat.copyFrom(locMat);
  61406. var origLocMatInv = Bone._tmpMats[1];
  61407. origLocMatInv.copyFrom(origLocMat);
  61408. origLocMatInv.invert();
  61409. var scaleMat = Bone._tmpMats[2];
  61410. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  61411. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  61412. this._scaleVector.x *= x;
  61413. this._scaleVector.y *= y;
  61414. this._scaleVector.z *= z;
  61415. locMat.multiplyToRef(origLocMatInv, locMat);
  61416. locMat.multiplyToRef(scaleMat, locMat);
  61417. locMat.multiplyToRef(origLocMat, locMat);
  61418. var parent = this.getParent();
  61419. if (parent) {
  61420. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  61421. }
  61422. else {
  61423. this.getAbsoluteTransform().copyFrom(locMat);
  61424. }
  61425. var len = this.children.length;
  61426. scaleMat.invert();
  61427. for (var i = 0; i < len; i++) {
  61428. var child = this.children[i];
  61429. var cm = child.getLocalMatrix();
  61430. cm.multiplyToRef(scaleMat, cm);
  61431. var lm = child.getLocalMatrix();
  61432. lm.m[12] *= x;
  61433. lm.m[13] *= y;
  61434. lm.m[14] *= z;
  61435. }
  61436. this.computeAbsoluteTransforms();
  61437. if (scaleChildren) {
  61438. for (var i = 0; i < len; i++) {
  61439. this.children[i].scale(x, y, z, scaleChildren);
  61440. }
  61441. }
  61442. this.markAsDirty();
  61443. };
  61444. /**
  61445. * Set the yaw, pitch, and roll of the bone in local or world space.
  61446. * @param yaw The rotation of the bone on the y axis.
  61447. * @param pitch The rotation of the bone on the x axis.
  61448. * @param roll The rotation of the bone on the z axis.
  61449. * @param space The space that the axes of rotation are in.
  61450. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61451. */
  61452. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  61453. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61454. var rotMat = Bone._tmpMats[0];
  61455. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  61456. var rotMatInv = Bone._tmpMats[1];
  61457. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  61458. rotMatInv.multiplyToRef(rotMat, rotMat);
  61459. this._rotateWithMatrix(rotMat, space, mesh);
  61460. };
  61461. /**
  61462. * Rotate the bone on an axis in local or world space.
  61463. * @param axis The axis to rotate the bone on.
  61464. * @param amount The amount to rotate the bone.
  61465. * @param space The space that the axis is in.
  61466. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61467. */
  61468. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  61469. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61470. var rmat = Bone._tmpMats[0];
  61471. rmat.m[12] = 0;
  61472. rmat.m[13] = 0;
  61473. rmat.m[14] = 0;
  61474. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  61475. this._rotateWithMatrix(rmat, space, mesh);
  61476. };
  61477. /**
  61478. * Set the rotation of the bone to a particular axis angle in local or world space.
  61479. * @param axis The axis to rotate the bone on.
  61480. * @param angle The angle that the bone should be rotated to.
  61481. * @param space The space that the axis is in.
  61482. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61483. */
  61484. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  61485. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61486. var rotMat = Bone._tmpMats[0];
  61487. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  61488. var rotMatInv = Bone._tmpMats[1];
  61489. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  61490. rotMatInv.multiplyToRef(rotMat, rotMat);
  61491. this._rotateWithMatrix(rotMat, space, mesh);
  61492. };
  61493. /**
  61494. * Set the euler rotation of the bone in local of world space.
  61495. * @param rotation The euler rotation that the bone should be set to.
  61496. * @param space The space that the rotation is in.
  61497. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61498. */
  61499. Bone.prototype.setRotation = function (rotation, space, mesh) {
  61500. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61501. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  61502. };
  61503. /**
  61504. * Set the quaternion rotation of the bone in local of world space.
  61505. * @param quat The quaternion rotation that the bone should be set to.
  61506. * @param space The space that the rotation is in.
  61507. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61508. */
  61509. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  61510. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61511. var rotMatInv = Bone._tmpMats[0];
  61512. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  61513. var rotMat = Bone._tmpMats[1];
  61514. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  61515. rotMatInv.multiplyToRef(rotMat, rotMat);
  61516. this._rotateWithMatrix(rotMat, space, mesh);
  61517. };
  61518. /**
  61519. * Set the rotation matrix of the bone in local of world space.
  61520. * @param rotMat The rotation matrix that the bone should be set to.
  61521. * @param space The space that the rotation is in.
  61522. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61523. */
  61524. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  61525. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61526. var rotMatInv = Bone._tmpMats[0];
  61527. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  61528. var rotMat2 = Bone._tmpMats[1];
  61529. rotMat2.copyFrom(rotMat);
  61530. rotMatInv.multiplyToRef(rotMat, rotMat2);
  61531. this._rotateWithMatrix(rotMat2, space, mesh);
  61532. };
  61533. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  61534. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61535. var lmat = this.getLocalMatrix();
  61536. var lx = lmat.m[12];
  61537. var ly = lmat.m[13];
  61538. var lz = lmat.m[14];
  61539. var parent = this.getParent();
  61540. var parentScale = Bone._tmpMats[3];
  61541. var parentScaleInv = Bone._tmpMats[4];
  61542. if (parent) {
  61543. if (space == BABYLON.Space.WORLD) {
  61544. if (mesh) {
  61545. parentScale.copyFrom(mesh.getWorldMatrix());
  61546. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  61547. }
  61548. else {
  61549. parentScale.copyFrom(parent.getAbsoluteTransform());
  61550. }
  61551. }
  61552. else {
  61553. parentScale = parent._scaleMatrix;
  61554. }
  61555. parentScaleInv.copyFrom(parentScale);
  61556. parentScaleInv.invert();
  61557. lmat.multiplyToRef(parentScale, lmat);
  61558. lmat.multiplyToRef(rmat, lmat);
  61559. lmat.multiplyToRef(parentScaleInv, lmat);
  61560. }
  61561. else {
  61562. if (space == BABYLON.Space.WORLD && mesh) {
  61563. parentScale.copyFrom(mesh.getWorldMatrix());
  61564. parentScaleInv.copyFrom(parentScale);
  61565. parentScaleInv.invert();
  61566. lmat.multiplyToRef(parentScale, lmat);
  61567. lmat.multiplyToRef(rmat, lmat);
  61568. lmat.multiplyToRef(parentScaleInv, lmat);
  61569. }
  61570. else {
  61571. lmat.multiplyToRef(rmat, lmat);
  61572. }
  61573. }
  61574. lmat.m[12] = lx;
  61575. lmat.m[13] = ly;
  61576. lmat.m[14] = lz;
  61577. this.computeAbsoluteTransforms();
  61578. this.markAsDirty();
  61579. };
  61580. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  61581. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61582. if (space == BABYLON.Space.WORLD) {
  61583. var scaleMatrix = Bone._tmpMats[2];
  61584. scaleMatrix.copyFrom(this._scaleMatrix);
  61585. rotMatInv.copyFrom(this.getAbsoluteTransform());
  61586. if (mesh) {
  61587. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  61588. var meshScale = Bone._tmpMats[3];
  61589. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  61590. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  61591. }
  61592. rotMatInv.invert();
  61593. scaleMatrix.m[0] *= this._scalingDeterminant;
  61594. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  61595. }
  61596. else {
  61597. rotMatInv.copyFrom(this.getLocalMatrix());
  61598. rotMatInv.invert();
  61599. var scaleMatrix = Bone._tmpMats[2];
  61600. scaleMatrix.copyFrom(this._scaleMatrix);
  61601. if (this._parent) {
  61602. var pscaleMatrix = Bone._tmpMats[3];
  61603. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  61604. pscaleMatrix.invert();
  61605. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  61606. }
  61607. else {
  61608. scaleMatrix.m[0] *= this._scalingDeterminant;
  61609. }
  61610. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  61611. }
  61612. };
  61613. /**
  61614. * Get the scale of the bone
  61615. * @returns the scale of the bone
  61616. */
  61617. Bone.prototype.getScale = function () {
  61618. return this._scaleVector.clone();
  61619. };
  61620. /**
  61621. * Copy the scale of the bone to a vector3.
  61622. * @param result The vector3 to copy the scale to
  61623. */
  61624. Bone.prototype.getScaleToRef = function (result) {
  61625. result.copyFrom(this._scaleVector);
  61626. };
  61627. /**
  61628. * Get the position of the bone in local or world space.
  61629. * @param space The space that the returned position is in.
  61630. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61631. * @returns The position of the bone
  61632. */
  61633. Bone.prototype.getPosition = function (space, mesh) {
  61634. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61635. if (mesh === void 0) { mesh = null; }
  61636. var pos = BABYLON.Vector3.Zero();
  61637. this.getPositionToRef(space, mesh, pos);
  61638. return pos;
  61639. };
  61640. /**
  61641. * Copy the position of the bone to a vector3 in local or world space.
  61642. * @param space The space that the returned position is in.
  61643. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61644. * @param result The vector3 to copy the position to.
  61645. */
  61646. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  61647. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61648. if (space == BABYLON.Space.LOCAL) {
  61649. var lm = this.getLocalMatrix();
  61650. result.x = lm.m[12];
  61651. result.y = lm.m[13];
  61652. result.z = lm.m[14];
  61653. }
  61654. else {
  61655. var wm = null;
  61656. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61657. if (mesh) {
  61658. wm = mesh.getWorldMatrix();
  61659. }
  61660. this._skeleton.computeAbsoluteTransforms();
  61661. var tmat = Bone._tmpMats[0];
  61662. if (mesh && wm) {
  61663. tmat.copyFrom(this.getAbsoluteTransform());
  61664. tmat.multiplyToRef(wm, tmat);
  61665. }
  61666. else {
  61667. tmat = this.getAbsoluteTransform();
  61668. }
  61669. result.x = tmat.m[12];
  61670. result.y = tmat.m[13];
  61671. result.z = tmat.m[14];
  61672. }
  61673. };
  61674. /**
  61675. * Get the absolute position of the bone (world space).
  61676. * @param mesh The mesh that this bone is attached to.
  61677. * @returns The absolute position of the bone
  61678. */
  61679. Bone.prototype.getAbsolutePosition = function (mesh) {
  61680. if (mesh === void 0) { mesh = null; }
  61681. var pos = BABYLON.Vector3.Zero();
  61682. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  61683. return pos;
  61684. };
  61685. /**
  61686. * Copy the absolute position of the bone (world space) to the result param.
  61687. * @param mesh The mesh that this bone is attached to.
  61688. * @param result The vector3 to copy the absolute position to.
  61689. */
  61690. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  61691. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  61692. };
  61693. /**
  61694. * Compute the absolute transforms of this bone and its children.
  61695. */
  61696. Bone.prototype.computeAbsoluteTransforms = function () {
  61697. if (this._parent) {
  61698. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  61699. }
  61700. else {
  61701. this._absoluteTransform.copyFrom(this._localMatrix);
  61702. var poseMatrix = this._skeleton.getPoseMatrix();
  61703. if (poseMatrix) {
  61704. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  61705. }
  61706. }
  61707. var children = this.children;
  61708. var len = children.length;
  61709. for (var i = 0; i < len; i++) {
  61710. children[i].computeAbsoluteTransforms();
  61711. }
  61712. };
  61713. Bone.prototype._syncScaleVector = function () {
  61714. var lm = this.getLocalMatrix();
  61715. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  61716. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  61717. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  61718. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  61719. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  61720. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  61721. this._scaleVector.x = xs * Math.sqrt(xsq);
  61722. this._scaleVector.y = ys * Math.sqrt(ysq);
  61723. this._scaleVector.z = zs * Math.sqrt(zsq);
  61724. if (this._parent) {
  61725. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  61726. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  61727. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  61728. }
  61729. 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);
  61730. };
  61731. /**
  61732. * Get the world direction from an axis that is in the local space of the bone.
  61733. * @param localAxis The local direction that is used to compute the world direction.
  61734. * @param mesh The mesh that this bone is attached to.
  61735. * @returns The world direction
  61736. */
  61737. Bone.prototype.getDirection = function (localAxis, mesh) {
  61738. if (mesh === void 0) { mesh = null; }
  61739. var result = BABYLON.Vector3.Zero();
  61740. this.getDirectionToRef(localAxis, mesh, result);
  61741. return result;
  61742. };
  61743. /**
  61744. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  61745. * @param localAxis The local direction that is used to compute the world direction.
  61746. * @param mesh The mesh that this bone is attached to.
  61747. * @param result The vector3 that the world direction will be copied to.
  61748. */
  61749. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  61750. if (mesh === void 0) { mesh = null; }
  61751. var wm = null;
  61752. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61753. if (mesh) {
  61754. wm = mesh.getWorldMatrix();
  61755. }
  61756. this._skeleton.computeAbsoluteTransforms();
  61757. var mat = Bone._tmpMats[0];
  61758. mat.copyFrom(this.getAbsoluteTransform());
  61759. if (mesh && wm) {
  61760. mat.multiplyToRef(wm, mat);
  61761. }
  61762. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  61763. result.normalize();
  61764. };
  61765. /**
  61766. * Get the euler rotation of the bone in local or world space.
  61767. * @param space The space that the rotation should be in.
  61768. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61769. * @returns The euler rotation
  61770. */
  61771. Bone.prototype.getRotation = function (space, mesh) {
  61772. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61773. if (mesh === void 0) { mesh = null; }
  61774. var result = BABYLON.Vector3.Zero();
  61775. this.getRotationToRef(space, mesh, result);
  61776. return result;
  61777. };
  61778. /**
  61779. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  61780. * @param space The space that the rotation should be in.
  61781. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61782. * @param result The vector3 that the rotation should be copied to.
  61783. */
  61784. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  61785. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61786. if (mesh === void 0) { mesh = null; }
  61787. var quat = Bone._tmpQuat;
  61788. this.getRotationQuaternionToRef(space, mesh, quat);
  61789. quat.toEulerAnglesToRef(result);
  61790. };
  61791. /**
  61792. * Get the quaternion rotation of the bone in either local or world space.
  61793. * @param space The space that the rotation should be in.
  61794. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61795. * @returns The quaternion rotation
  61796. */
  61797. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  61798. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61799. if (mesh === void 0) { mesh = null; }
  61800. var result = BABYLON.Quaternion.Identity();
  61801. this.getRotationQuaternionToRef(space, mesh, result);
  61802. return result;
  61803. };
  61804. /**
  61805. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  61806. * @param space The space that the rotation should be in.
  61807. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61808. * @param result The quaternion that the rotation should be copied to.
  61809. */
  61810. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  61811. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61812. if (mesh === void 0) { mesh = null; }
  61813. if (space == BABYLON.Space.LOCAL) {
  61814. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  61815. }
  61816. else {
  61817. var mat = Bone._tmpMats[0];
  61818. var amat = this.getAbsoluteTransform();
  61819. if (mesh) {
  61820. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  61821. }
  61822. else {
  61823. mat.copyFrom(amat);
  61824. }
  61825. mat.m[0] *= this._scalingDeterminant;
  61826. mat.m[1] *= this._scalingDeterminant;
  61827. mat.m[2] *= this._scalingDeterminant;
  61828. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  61829. }
  61830. };
  61831. /**
  61832. * Get the rotation matrix of the bone in local or world space.
  61833. * @param space The space that the rotation should be in.
  61834. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61835. * @returns The rotation matrix
  61836. */
  61837. Bone.prototype.getRotationMatrix = function (space, mesh) {
  61838. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61839. var result = BABYLON.Matrix.Identity();
  61840. this.getRotationMatrixToRef(space, mesh, result);
  61841. return result;
  61842. };
  61843. /**
  61844. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  61845. * @param space The space that the rotation should be in.
  61846. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61847. * @param result The quaternion that the rotation should be copied to.
  61848. */
  61849. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  61850. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61851. if (space == BABYLON.Space.LOCAL) {
  61852. this.getLocalMatrix().getRotationMatrixToRef(result);
  61853. }
  61854. else {
  61855. var mat = Bone._tmpMats[0];
  61856. var amat = this.getAbsoluteTransform();
  61857. if (mesh) {
  61858. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  61859. }
  61860. else {
  61861. mat.copyFrom(amat);
  61862. }
  61863. mat.m[0] *= this._scalingDeterminant;
  61864. mat.m[1] *= this._scalingDeterminant;
  61865. mat.m[2] *= this._scalingDeterminant;
  61866. mat.getRotationMatrixToRef(result);
  61867. }
  61868. };
  61869. /**
  61870. * Get the world position of a point that is in the local space of the bone.
  61871. * @param position The local position
  61872. * @param mesh The mesh that this bone is attached to.
  61873. * @returns The world position
  61874. */
  61875. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  61876. if (mesh === void 0) { mesh = null; }
  61877. var result = BABYLON.Vector3.Zero();
  61878. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  61879. return result;
  61880. };
  61881. /**
  61882. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  61883. * @param position The local position
  61884. * @param mesh The mesh that this bone is attached to.
  61885. * @param result The vector3 that the world position should be copied to.
  61886. */
  61887. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  61888. if (mesh === void 0) { mesh = null; }
  61889. var wm = null;
  61890. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61891. if (mesh) {
  61892. wm = mesh.getWorldMatrix();
  61893. }
  61894. this._skeleton.computeAbsoluteTransforms();
  61895. var tmat = Bone._tmpMats[0];
  61896. if (mesh && wm) {
  61897. tmat.copyFrom(this.getAbsoluteTransform());
  61898. tmat.multiplyToRef(wm, tmat);
  61899. }
  61900. else {
  61901. tmat = this.getAbsoluteTransform();
  61902. }
  61903. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  61904. };
  61905. /**
  61906. * Get the local position of a point that is in world space.
  61907. * @param position The world position
  61908. * @param mesh The mesh that this bone is attached to.
  61909. * @returns The local position
  61910. */
  61911. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  61912. if (mesh === void 0) { mesh = null; }
  61913. var result = BABYLON.Vector3.Zero();
  61914. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  61915. return result;
  61916. };
  61917. /**
  61918. * Get the local position of a point that is in world space and copy it to the result param.
  61919. * @param position The world position
  61920. * @param mesh The mesh that this bone is attached to.
  61921. * @param result The vector3 that the local position should be copied to.
  61922. */
  61923. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  61924. if (mesh === void 0) { mesh = null; }
  61925. var wm = null;
  61926. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61927. if (mesh) {
  61928. wm = mesh.getWorldMatrix();
  61929. }
  61930. this._skeleton.computeAbsoluteTransforms();
  61931. var tmat = Bone._tmpMats[0];
  61932. tmat.copyFrom(this.getAbsoluteTransform());
  61933. if (mesh && wm) {
  61934. tmat.multiplyToRef(wm, tmat);
  61935. }
  61936. tmat.invert();
  61937. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  61938. };
  61939. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61940. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  61941. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61942. return Bone;
  61943. }(BABYLON.Node));
  61944. BABYLON.Bone = Bone;
  61945. })(BABYLON || (BABYLON = {}));
  61946. //# sourceMappingURL=babylon.bone.js.map
  61947. var BABYLON;
  61948. (function (BABYLON) {
  61949. var BoneIKController = /** @class */ (function () {
  61950. function BoneIKController(mesh, bone, options) {
  61951. this.targetPosition = BABYLON.Vector3.Zero();
  61952. this.poleTargetPosition = BABYLON.Vector3.Zero();
  61953. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  61954. this.poleAngle = 0;
  61955. this.slerpAmount = 1;
  61956. this._bone1Quat = BABYLON.Quaternion.Identity();
  61957. this._bone1Mat = BABYLON.Matrix.Identity();
  61958. this._bone2Ang = Math.PI;
  61959. this._maxAngle = Math.PI;
  61960. this._rightHandedSystem = false;
  61961. this._bendAxis = BABYLON.Vector3.Right();
  61962. this._slerping = false;
  61963. this._adjustRoll = 0;
  61964. this._bone2 = bone;
  61965. this._bone1 = bone.getParent();
  61966. if (!this._bone1) {
  61967. return;
  61968. }
  61969. this.mesh = mesh;
  61970. var bonePos = bone.getPosition();
  61971. if (bone.getAbsoluteTransform().determinant() > 0) {
  61972. this._rightHandedSystem = true;
  61973. this._bendAxis.x = 0;
  61974. this._bendAxis.y = 0;
  61975. this._bendAxis.z = -1;
  61976. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  61977. this._adjustRoll = Math.PI * .5;
  61978. this._bendAxis.z = 1;
  61979. }
  61980. }
  61981. if (this._bone1.length) {
  61982. var boneScale1 = this._bone1.getScale();
  61983. var boneScale2 = this._bone2.getScale();
  61984. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  61985. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  61986. }
  61987. else if (this._bone1.children[0]) {
  61988. mesh.computeWorldMatrix(true);
  61989. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  61990. var pos2 = this._bone2.getAbsolutePosition(mesh);
  61991. var pos3 = this._bone1.getAbsolutePosition(mesh);
  61992. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  61993. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  61994. }
  61995. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  61996. this.maxAngle = Math.PI;
  61997. if (options) {
  61998. if (options.targetMesh) {
  61999. this.targetMesh = options.targetMesh;
  62000. this.targetMesh.computeWorldMatrix(true);
  62001. }
  62002. if (options.poleTargetMesh) {
  62003. this.poleTargetMesh = options.poleTargetMesh;
  62004. this.poleTargetMesh.computeWorldMatrix(true);
  62005. }
  62006. else if (options.poleTargetBone) {
  62007. this.poleTargetBone = options.poleTargetBone;
  62008. }
  62009. else if (this._bone1.getParent()) {
  62010. this.poleTargetBone = this._bone1.getParent();
  62011. }
  62012. if (options.poleTargetLocalOffset) {
  62013. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  62014. }
  62015. if (options.poleAngle) {
  62016. this.poleAngle = options.poleAngle;
  62017. }
  62018. if (options.bendAxis) {
  62019. this._bendAxis.copyFrom(options.bendAxis);
  62020. }
  62021. if (options.maxAngle) {
  62022. this.maxAngle = options.maxAngle;
  62023. }
  62024. if (options.slerpAmount) {
  62025. this.slerpAmount = options.slerpAmount;
  62026. }
  62027. }
  62028. }
  62029. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  62030. get: function () {
  62031. return this._maxAngle;
  62032. },
  62033. set: function (value) {
  62034. this._setMaxAngle(value);
  62035. },
  62036. enumerable: true,
  62037. configurable: true
  62038. });
  62039. BoneIKController.prototype._setMaxAngle = function (ang) {
  62040. if (ang < 0) {
  62041. ang = 0;
  62042. }
  62043. if (ang > Math.PI || ang == undefined) {
  62044. ang = Math.PI;
  62045. }
  62046. this._maxAngle = ang;
  62047. var a = this._bone1Length;
  62048. var b = this._bone2Length;
  62049. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  62050. };
  62051. BoneIKController.prototype.update = function () {
  62052. var bone1 = this._bone1;
  62053. if (!bone1) {
  62054. return;
  62055. }
  62056. var target = this.targetPosition;
  62057. var poleTarget = this.poleTargetPosition;
  62058. var mat1 = BoneIKController._tmpMats[0];
  62059. var mat2 = BoneIKController._tmpMats[1];
  62060. if (this.targetMesh) {
  62061. target.copyFrom(this.targetMesh.getAbsolutePosition());
  62062. }
  62063. if (this.poleTargetBone) {
  62064. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  62065. }
  62066. else if (this.poleTargetMesh) {
  62067. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  62068. }
  62069. var bonePos = BoneIKController._tmpVecs[0];
  62070. var zaxis = BoneIKController._tmpVecs[1];
  62071. var xaxis = BoneIKController._tmpVecs[2];
  62072. var yaxis = BoneIKController._tmpVecs[3];
  62073. var upAxis = BoneIKController._tmpVecs[4];
  62074. var _tmpQuat = BoneIKController._tmpQuat;
  62075. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  62076. poleTarget.subtractToRef(bonePos, upAxis);
  62077. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  62078. upAxis.y = 1;
  62079. }
  62080. else {
  62081. upAxis.normalize();
  62082. }
  62083. target.subtractToRef(bonePos, yaxis);
  62084. yaxis.normalize();
  62085. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  62086. zaxis.normalize();
  62087. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  62088. xaxis.normalize();
  62089. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  62090. var a = this._bone1Length;
  62091. var b = this._bone2Length;
  62092. var c = BABYLON.Vector3.Distance(bonePos, target);
  62093. if (this._maxReach > 0) {
  62094. c = Math.min(this._maxReach, c);
  62095. }
  62096. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  62097. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  62098. if (acosa > 1) {
  62099. acosa = 1;
  62100. }
  62101. if (acosb > 1) {
  62102. acosb = 1;
  62103. }
  62104. if (acosa < -1) {
  62105. acosa = -1;
  62106. }
  62107. if (acosb < -1) {
  62108. acosb = -1;
  62109. }
  62110. var angA = Math.acos(acosa);
  62111. var angB = Math.acos(acosb);
  62112. var angC = -angA - angB;
  62113. if (this._rightHandedSystem) {
  62114. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  62115. mat2.multiplyToRef(mat1, mat1);
  62116. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  62117. mat2.multiplyToRef(mat1, mat1);
  62118. }
  62119. else {
  62120. var _tmpVec = BoneIKController._tmpVecs[5];
  62121. _tmpVec.copyFrom(this._bendAxis);
  62122. _tmpVec.x *= -1;
  62123. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  62124. mat2.multiplyToRef(mat1, mat1);
  62125. }
  62126. if (this.poleAngle) {
  62127. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  62128. mat1.multiplyToRef(mat2, mat1);
  62129. }
  62130. if (this._bone1) {
  62131. if (this.slerpAmount < 1) {
  62132. if (!this._slerping) {
  62133. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  62134. }
  62135. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  62136. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  62137. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  62138. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  62139. this._slerping = true;
  62140. }
  62141. else {
  62142. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  62143. this._bone1Mat.copyFrom(mat1);
  62144. this._slerping = false;
  62145. }
  62146. }
  62147. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  62148. this._bone2Ang = angC;
  62149. };
  62150. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62151. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  62152. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  62153. return BoneIKController;
  62154. }());
  62155. BABYLON.BoneIKController = BoneIKController;
  62156. })(BABYLON || (BABYLON = {}));
  62157. //# sourceMappingURL=babylon.boneIKController.js.map
  62158. var BABYLON;
  62159. (function (BABYLON) {
  62160. var BoneLookController = /** @class */ (function () {
  62161. /**
  62162. * Create a BoneLookController
  62163. * @param mesh the mesh that the bone belongs to
  62164. * @param bone the bone that will be looking to the target
  62165. * @param target the target Vector3 to look at
  62166. * @param settings optional settings:
  62167. * - maxYaw: the maximum angle the bone will yaw to
  62168. * - minYaw: the minimum angle the bone will yaw to
  62169. * - maxPitch: the maximum angle the bone will pitch to
  62170. * - minPitch: the minimum angle the bone will yaw to
  62171. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  62172. * - upAxis: the up axis of the coordinate system
  62173. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  62174. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  62175. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  62176. * - adjustYaw: used to make an adjustment to the yaw of the bone
  62177. * - adjustPitch: used to make an adjustment to the pitch of the bone
  62178. * - adjustRoll: used to make an adjustment to the roll of the bone
  62179. **/
  62180. function BoneLookController(mesh, bone, target, options) {
  62181. /**
  62182. * The up axis of the coordinate system that is used when the bone is rotated.
  62183. */
  62184. this.upAxis = BABYLON.Vector3.Up();
  62185. /**
  62186. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  62187. */
  62188. this.upAxisSpace = BABYLON.Space.LOCAL;
  62189. /**
  62190. * Used to make an adjustment to the yaw of the bone.
  62191. */
  62192. this.adjustYaw = 0;
  62193. /**
  62194. * Used to make an adjustment to the pitch of the bone.
  62195. */
  62196. this.adjustPitch = 0;
  62197. /**
  62198. * Used to make an adjustment to the roll of the bone.
  62199. */
  62200. this.adjustRoll = 0;
  62201. /**
  62202. * 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).
  62203. */
  62204. this.slerpAmount = 1;
  62205. this._boneQuat = BABYLON.Quaternion.Identity();
  62206. this._slerping = false;
  62207. this._firstFrameSkipped = false;
  62208. this._fowardAxis = BABYLON.Vector3.Forward();
  62209. this.mesh = mesh;
  62210. this.bone = bone;
  62211. this.target = target;
  62212. if (options) {
  62213. if (options.adjustYaw) {
  62214. this.adjustYaw = options.adjustYaw;
  62215. }
  62216. if (options.adjustPitch) {
  62217. this.adjustPitch = options.adjustPitch;
  62218. }
  62219. if (options.adjustRoll) {
  62220. this.adjustRoll = options.adjustRoll;
  62221. }
  62222. if (options.maxYaw != null) {
  62223. this.maxYaw = options.maxYaw;
  62224. }
  62225. else {
  62226. this.maxYaw = Math.PI;
  62227. }
  62228. if (options.minYaw != null) {
  62229. this.minYaw = options.minYaw;
  62230. }
  62231. else {
  62232. this.minYaw = -Math.PI;
  62233. }
  62234. if (options.maxPitch != null) {
  62235. this.maxPitch = options.maxPitch;
  62236. }
  62237. else {
  62238. this.maxPitch = Math.PI;
  62239. }
  62240. if (options.minPitch != null) {
  62241. this.minPitch = options.minPitch;
  62242. }
  62243. else {
  62244. this.minPitch = -Math.PI;
  62245. }
  62246. if (options.slerpAmount != null) {
  62247. this.slerpAmount = options.slerpAmount;
  62248. }
  62249. if (options.upAxis != null) {
  62250. this.upAxis = options.upAxis;
  62251. }
  62252. if (options.upAxisSpace != null) {
  62253. this.upAxisSpace = options.upAxisSpace;
  62254. }
  62255. if (options.yawAxis != null || options.pitchAxis != null) {
  62256. var newYawAxis = BABYLON.Axis.Y;
  62257. var newPitchAxis = BABYLON.Axis.X;
  62258. if (options.yawAxis != null) {
  62259. newYawAxis = options.yawAxis.clone();
  62260. newYawAxis.normalize();
  62261. }
  62262. if (options.pitchAxis != null) {
  62263. newPitchAxis = options.pitchAxis.clone();
  62264. newPitchAxis.normalize();
  62265. }
  62266. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  62267. this._transformYawPitch = BABYLON.Matrix.Identity();
  62268. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  62269. this._transformYawPitchInv = this._transformYawPitch.clone();
  62270. this._transformYawPitch.invert();
  62271. }
  62272. }
  62273. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  62274. this.upAxisSpace = BABYLON.Space.LOCAL;
  62275. }
  62276. }
  62277. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  62278. /**
  62279. * Get/set the minimum yaw angle that the bone can look to.
  62280. */
  62281. get: function () {
  62282. return this._minYaw;
  62283. },
  62284. set: function (value) {
  62285. this._minYaw = value;
  62286. this._minYawSin = Math.sin(value);
  62287. this._minYawCos = Math.cos(value);
  62288. if (this._maxYaw != null) {
  62289. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  62290. this._yawRange = this._maxYaw - this._minYaw;
  62291. }
  62292. },
  62293. enumerable: true,
  62294. configurable: true
  62295. });
  62296. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  62297. /**
  62298. * Get/set the maximum yaw angle that the bone can look to.
  62299. */
  62300. get: function () {
  62301. return this._maxYaw;
  62302. },
  62303. set: function (value) {
  62304. this._maxYaw = value;
  62305. this._maxYawSin = Math.sin(value);
  62306. this._maxYawCos = Math.cos(value);
  62307. if (this._minYaw != null) {
  62308. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  62309. this._yawRange = this._maxYaw - this._minYaw;
  62310. }
  62311. },
  62312. enumerable: true,
  62313. configurable: true
  62314. });
  62315. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  62316. /**
  62317. * Get/set the minimum pitch angle that the bone can look to.
  62318. */
  62319. get: function () {
  62320. return this._minPitch;
  62321. },
  62322. set: function (value) {
  62323. this._minPitch = value;
  62324. this._minPitchTan = Math.tan(value);
  62325. },
  62326. enumerable: true,
  62327. configurable: true
  62328. });
  62329. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  62330. /**
  62331. * Get/set the maximum pitch angle that the bone can look to.
  62332. */
  62333. get: function () {
  62334. return this._maxPitch;
  62335. },
  62336. set: function (value) {
  62337. this._maxPitch = value;
  62338. this._maxPitchTan = Math.tan(value);
  62339. },
  62340. enumerable: true,
  62341. configurable: true
  62342. });
  62343. /**
  62344. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  62345. */
  62346. BoneLookController.prototype.update = function () {
  62347. //skip the first frame when slerping so that the mesh rotation is correct
  62348. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  62349. this._firstFrameSkipped = true;
  62350. return;
  62351. }
  62352. var bone = this.bone;
  62353. var bonePos = BoneLookController._tmpVecs[0];
  62354. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  62355. var target = this.target;
  62356. var _tmpMat1 = BoneLookController._tmpMats[0];
  62357. var _tmpMat2 = BoneLookController._tmpMats[1];
  62358. var mesh = this.mesh;
  62359. var parentBone = bone.getParent();
  62360. var upAxis = BoneLookController._tmpVecs[1];
  62361. upAxis.copyFrom(this.upAxis);
  62362. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  62363. if (this._transformYawPitch) {
  62364. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  62365. }
  62366. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  62367. }
  62368. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  62369. mesh.getDirectionToRef(upAxis, upAxis);
  62370. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  62371. upAxis.normalize();
  62372. }
  62373. }
  62374. var checkYaw = false;
  62375. var checkPitch = false;
  62376. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  62377. checkYaw = true;
  62378. }
  62379. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  62380. checkPitch = true;
  62381. }
  62382. if (checkYaw || checkPitch) {
  62383. var spaceMat = BoneLookController._tmpMats[2];
  62384. var spaceMatInv = BoneLookController._tmpMats[3];
  62385. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  62386. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  62387. }
  62388. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  62389. spaceMat.copyFrom(mesh.getWorldMatrix());
  62390. }
  62391. else {
  62392. var forwardAxis = BoneLookController._tmpVecs[2];
  62393. forwardAxis.copyFrom(this._fowardAxis);
  62394. if (this._transformYawPitch) {
  62395. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  62396. }
  62397. if (parentBone) {
  62398. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  62399. }
  62400. else {
  62401. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  62402. }
  62403. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  62404. rightAxis.normalize();
  62405. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  62406. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  62407. }
  62408. spaceMat.invertToRef(spaceMatInv);
  62409. var xzlen = null;
  62410. if (checkPitch) {
  62411. var localTarget = BoneLookController._tmpVecs[3];
  62412. target.subtractToRef(bonePos, localTarget);
  62413. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  62414. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  62415. var pitch = Math.atan2(localTarget.y, xzlen);
  62416. var newPitch = pitch;
  62417. if (pitch > this._maxPitch) {
  62418. localTarget.y = this._maxPitchTan * xzlen;
  62419. newPitch = this._maxPitch;
  62420. }
  62421. else if (pitch < this._minPitch) {
  62422. localTarget.y = this._minPitchTan * xzlen;
  62423. newPitch = this._minPitch;
  62424. }
  62425. if (pitch != newPitch) {
  62426. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  62427. localTarget.addInPlace(bonePos);
  62428. target = localTarget;
  62429. }
  62430. }
  62431. if (checkYaw) {
  62432. var localTarget = BoneLookController._tmpVecs[4];
  62433. target.subtractToRef(bonePos, localTarget);
  62434. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  62435. var yaw = Math.atan2(localTarget.x, localTarget.z);
  62436. var newYaw = yaw;
  62437. if (yaw > this._maxYaw || yaw < this._minYaw) {
  62438. if (xzlen == null) {
  62439. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  62440. }
  62441. if (this._yawRange > Math.PI) {
  62442. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  62443. localTarget.z = this._maxYawCos * xzlen;
  62444. localTarget.x = this._maxYawSin * xzlen;
  62445. newYaw = this._maxYaw;
  62446. }
  62447. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  62448. localTarget.z = this._minYawCos * xzlen;
  62449. localTarget.x = this._minYawSin * xzlen;
  62450. newYaw = this._minYaw;
  62451. }
  62452. }
  62453. else {
  62454. if (yaw > this._maxYaw) {
  62455. localTarget.z = this._maxYawCos * xzlen;
  62456. localTarget.x = this._maxYawSin * xzlen;
  62457. newYaw = this._maxYaw;
  62458. }
  62459. else if (yaw < this._minYaw) {
  62460. localTarget.z = this._minYawCos * xzlen;
  62461. localTarget.x = this._minYawSin * xzlen;
  62462. newYaw = this._minYaw;
  62463. }
  62464. }
  62465. }
  62466. if (this._slerping && this._yawRange > Math.PI) {
  62467. //are we going to be crossing into the min/max region?
  62468. var boneFwd = BoneLookController._tmpVecs[8];
  62469. boneFwd.copyFrom(BABYLON.Axis.Z);
  62470. if (this._transformYawPitch) {
  62471. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  62472. }
  62473. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  62474. this._boneQuat.toRotationMatrix(boneRotMat);
  62475. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  62476. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  62477. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  62478. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  62479. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  62480. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  62481. if (angBtwTar > angBtwMidYaw) {
  62482. if (xzlen == null) {
  62483. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  62484. }
  62485. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  62486. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  62487. if (angBtwMin < angBtwMax) {
  62488. newYaw = boneYaw + Math.PI * .75;
  62489. localTarget.z = Math.cos(newYaw) * xzlen;
  62490. localTarget.x = Math.sin(newYaw) * xzlen;
  62491. }
  62492. else {
  62493. newYaw = boneYaw - Math.PI * .75;
  62494. localTarget.z = Math.cos(newYaw) * xzlen;
  62495. localTarget.x = Math.sin(newYaw) * xzlen;
  62496. }
  62497. }
  62498. }
  62499. if (yaw != newYaw) {
  62500. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  62501. localTarget.addInPlace(bonePos);
  62502. target = localTarget;
  62503. }
  62504. }
  62505. }
  62506. var zaxis = BoneLookController._tmpVecs[5];
  62507. var xaxis = BoneLookController._tmpVecs[6];
  62508. var yaxis = BoneLookController._tmpVecs[7];
  62509. var _tmpQuat = BoneLookController._tmpQuat;
  62510. target.subtractToRef(bonePos, zaxis);
  62511. zaxis.normalize();
  62512. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  62513. xaxis.normalize();
  62514. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  62515. yaxis.normalize();
  62516. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  62517. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  62518. return;
  62519. }
  62520. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  62521. return;
  62522. }
  62523. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  62524. return;
  62525. }
  62526. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  62527. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  62528. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  62529. }
  62530. if (this.slerpAmount < 1) {
  62531. if (!this._slerping) {
  62532. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  62533. }
  62534. if (this._transformYawPitch) {
  62535. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  62536. }
  62537. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  62538. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  62539. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  62540. this._slerping = true;
  62541. }
  62542. else {
  62543. if (this._transformYawPitch) {
  62544. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  62545. }
  62546. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  62547. this._slerping = false;
  62548. }
  62549. };
  62550. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  62551. var angDiff = ang2 - ang1;
  62552. angDiff %= Math.PI * 2;
  62553. if (angDiff > Math.PI) {
  62554. angDiff -= Math.PI * 2;
  62555. }
  62556. else if (angDiff < -Math.PI) {
  62557. angDiff += Math.PI * 2;
  62558. }
  62559. return angDiff;
  62560. };
  62561. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  62562. ang1 %= (2 * Math.PI);
  62563. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  62564. ang2 %= (2 * Math.PI);
  62565. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  62566. var ab = 0;
  62567. if (ang1 < ang2) {
  62568. ab = ang2 - ang1;
  62569. }
  62570. else {
  62571. ab = ang1 - ang2;
  62572. }
  62573. if (ab > Math.PI) {
  62574. ab = Math.PI * 2 - ab;
  62575. }
  62576. return ab;
  62577. };
  62578. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  62579. ang %= (2 * Math.PI);
  62580. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  62581. ang1 %= (2 * Math.PI);
  62582. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  62583. ang2 %= (2 * Math.PI);
  62584. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  62585. if (ang1 < ang2) {
  62586. if (ang > ang1 && ang < ang2) {
  62587. return true;
  62588. }
  62589. }
  62590. else {
  62591. if (ang > ang2 && ang < ang1) {
  62592. return true;
  62593. }
  62594. }
  62595. return false;
  62596. };
  62597. 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()];
  62598. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  62599. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  62600. return BoneLookController;
  62601. }());
  62602. BABYLON.BoneLookController = BoneLookController;
  62603. })(BABYLON || (BABYLON = {}));
  62604. //# sourceMappingURL=babylon.boneLookController.js.map
  62605. var BABYLON;
  62606. (function (BABYLON) {
  62607. var Skeleton = /** @class */ (function () {
  62608. function Skeleton(name, id, scene) {
  62609. this.name = name;
  62610. this.id = id;
  62611. this.bones = new Array();
  62612. this.needInitialSkinMatrix = false;
  62613. this._isDirty = true;
  62614. this._meshesWithPoseMatrix = new Array();
  62615. this._identity = BABYLON.Matrix.Identity();
  62616. this._ranges = {};
  62617. this._lastAbsoluteTransformsUpdateId = -1;
  62618. // Events
  62619. /**
  62620. * An event triggered before computing the skeleton's matrices
  62621. * @type {BABYLON.Observable}
  62622. */
  62623. this.onBeforeComputeObservable = new BABYLON.Observable();
  62624. this.bones = [];
  62625. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62626. scene.skeletons.push(this);
  62627. //make sure it will recalculate the matrix next time prepare is called.
  62628. this._isDirty = true;
  62629. }
  62630. // Members
  62631. Skeleton.prototype.getTransformMatrices = function (mesh) {
  62632. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  62633. return mesh._bonesTransformMatrices;
  62634. }
  62635. if (!this._transformMatrices) {
  62636. this.prepare();
  62637. }
  62638. return this._transformMatrices;
  62639. };
  62640. Skeleton.prototype.getScene = function () {
  62641. return this._scene;
  62642. };
  62643. // Methods
  62644. /**
  62645. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  62646. */
  62647. Skeleton.prototype.toString = function (fullDetails) {
  62648. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  62649. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  62650. if (fullDetails) {
  62651. ret += ", Ranges: {";
  62652. var first = true;
  62653. for (var name_1 in this._ranges) {
  62654. if (first) {
  62655. ret += ", ";
  62656. first = false;
  62657. }
  62658. ret += name_1;
  62659. }
  62660. ret += "}";
  62661. }
  62662. return ret;
  62663. };
  62664. /**
  62665. * Get bone's index searching by name
  62666. * @param {string} name is bone's name to search for
  62667. * @return {number} Indice of the bone. Returns -1 if not found
  62668. */
  62669. Skeleton.prototype.getBoneIndexByName = function (name) {
  62670. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  62671. if (this.bones[boneIndex].name === name) {
  62672. return boneIndex;
  62673. }
  62674. }
  62675. return -1;
  62676. };
  62677. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  62678. // check name not already in use
  62679. if (!this._ranges[name]) {
  62680. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  62681. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  62682. if (this.bones[i].animations[0]) {
  62683. this.bones[i].animations[0].createRange(name, from, to);
  62684. }
  62685. }
  62686. }
  62687. };
  62688. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  62689. if (deleteFrames === void 0) { deleteFrames = true; }
  62690. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  62691. if (this.bones[i].animations[0]) {
  62692. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  62693. }
  62694. }
  62695. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  62696. };
  62697. Skeleton.prototype.getAnimationRange = function (name) {
  62698. return this._ranges[name];
  62699. };
  62700. /**
  62701. * Returns as an Array, all AnimationRanges defined on this skeleton
  62702. */
  62703. Skeleton.prototype.getAnimationRanges = function () {
  62704. var animationRanges = [];
  62705. var name;
  62706. var i = 0;
  62707. for (name in this._ranges) {
  62708. animationRanges[i] = this._ranges[name];
  62709. i++;
  62710. }
  62711. return animationRanges;
  62712. };
  62713. /**
  62714. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  62715. */
  62716. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  62717. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  62718. if (this._ranges[name] || !source.getAnimationRange(name)) {
  62719. return false;
  62720. }
  62721. var ret = true;
  62722. var frameOffset = this._getHighestAnimationFrame() + 1;
  62723. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  62724. var boneDict = {};
  62725. var sourceBones = source.bones;
  62726. var nBones;
  62727. var i;
  62728. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  62729. boneDict[sourceBones[i].name] = sourceBones[i];
  62730. }
  62731. if (this.bones.length !== sourceBones.length) {
  62732. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  62733. ret = false;
  62734. }
  62735. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  62736. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  62737. var boneName = this.bones[i].name;
  62738. var sourceBone = boneDict[boneName];
  62739. if (sourceBone) {
  62740. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  62741. }
  62742. else {
  62743. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  62744. ret = false;
  62745. }
  62746. }
  62747. // do not call createAnimationRange(), since it also is done to bones, which was already done
  62748. var range = source.getAnimationRange(name);
  62749. if (range) {
  62750. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  62751. }
  62752. return ret;
  62753. };
  62754. Skeleton.prototype.returnToRest = function () {
  62755. for (var index = 0; index < this.bones.length; index++) {
  62756. this.bones[index].returnToRest();
  62757. }
  62758. };
  62759. Skeleton.prototype._getHighestAnimationFrame = function () {
  62760. var ret = 0;
  62761. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  62762. if (this.bones[i].animations[0]) {
  62763. var highest = this.bones[i].animations[0].getHighestFrame();
  62764. if (ret < highest) {
  62765. ret = highest;
  62766. }
  62767. }
  62768. }
  62769. return ret;
  62770. };
  62771. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  62772. var range = this.getAnimationRange(name);
  62773. if (!range) {
  62774. return null;
  62775. }
  62776. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  62777. };
  62778. Skeleton.prototype._markAsDirty = function () {
  62779. this._isDirty = true;
  62780. };
  62781. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  62782. this._meshesWithPoseMatrix.push(mesh);
  62783. };
  62784. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  62785. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  62786. if (index > -1) {
  62787. this._meshesWithPoseMatrix.splice(index, 1);
  62788. }
  62789. };
  62790. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  62791. this.onBeforeComputeObservable.notifyObservers(this);
  62792. for (var index = 0; index < this.bones.length; index++) {
  62793. var bone = this.bones[index];
  62794. var parentBone = bone.getParent();
  62795. if (parentBone) {
  62796. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  62797. }
  62798. else {
  62799. if (initialSkinMatrix) {
  62800. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  62801. }
  62802. else {
  62803. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  62804. }
  62805. }
  62806. if (bone._index !== -1) {
  62807. var mappedIndex = bone._index === null ? index : bone._index;
  62808. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  62809. }
  62810. }
  62811. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  62812. };
  62813. Skeleton.prototype.prepare = function () {
  62814. if (!this._isDirty) {
  62815. return;
  62816. }
  62817. if (this.needInitialSkinMatrix) {
  62818. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  62819. var mesh = this._meshesWithPoseMatrix[index];
  62820. var poseMatrix = mesh.getPoseMatrix();
  62821. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  62822. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  62823. }
  62824. if (this._synchronizedWithMesh !== mesh) {
  62825. this._synchronizedWithMesh = mesh;
  62826. // Prepare bones
  62827. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  62828. var bone = this.bones[boneIndex];
  62829. if (!bone.getParent()) {
  62830. var matrix = bone.getBaseMatrix();
  62831. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  62832. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  62833. }
  62834. }
  62835. }
  62836. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  62837. }
  62838. }
  62839. else {
  62840. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  62841. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  62842. }
  62843. this._computeTransformMatrices(this._transformMatrices, null);
  62844. }
  62845. this._isDirty = false;
  62846. this._scene._activeBones.addCount(this.bones.length, false);
  62847. };
  62848. Skeleton.prototype.getAnimatables = function () {
  62849. if (!this._animatables || this._animatables.length !== this.bones.length) {
  62850. this._animatables = [];
  62851. for (var index = 0; index < this.bones.length; index++) {
  62852. this._animatables.push(this.bones[index]);
  62853. }
  62854. }
  62855. return this._animatables;
  62856. };
  62857. Skeleton.prototype.clone = function (name, id) {
  62858. var result = new Skeleton(name, id || name, this._scene);
  62859. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  62860. for (var index = 0; index < this.bones.length; index++) {
  62861. var source = this.bones[index];
  62862. var parentBone = null;
  62863. var parent_1 = source.getParent();
  62864. if (parent_1) {
  62865. var parentIndex = this.bones.indexOf(parent_1);
  62866. parentBone = result.bones[parentIndex];
  62867. }
  62868. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  62869. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  62870. }
  62871. if (this._ranges) {
  62872. result._ranges = {};
  62873. for (var rangeName in this._ranges) {
  62874. var range = this._ranges[rangeName];
  62875. if (range) {
  62876. result._ranges[rangeName] = range.clone();
  62877. }
  62878. }
  62879. }
  62880. this._isDirty = true;
  62881. return result;
  62882. };
  62883. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  62884. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  62885. this.bones.forEach(function (bone) {
  62886. bone.animations.forEach(function (animation) {
  62887. animation.enableBlending = true;
  62888. animation.blendingSpeed = blendingSpeed;
  62889. });
  62890. });
  62891. };
  62892. Skeleton.prototype.dispose = function () {
  62893. this._meshesWithPoseMatrix = [];
  62894. // Animations
  62895. this.getScene().stopAnimation(this);
  62896. // Remove from scene
  62897. this.getScene().removeSkeleton(this);
  62898. };
  62899. Skeleton.prototype.serialize = function () {
  62900. var serializationObject = {};
  62901. serializationObject.name = this.name;
  62902. serializationObject.id = this.id;
  62903. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  62904. serializationObject.bones = [];
  62905. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  62906. for (var index = 0; index < this.bones.length; index++) {
  62907. var bone = this.bones[index];
  62908. var parent_2 = bone.getParent();
  62909. var serializedBone = {
  62910. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  62911. name: bone.name,
  62912. matrix: bone.getBaseMatrix().toArray(),
  62913. rest: bone.getRestPose().toArray()
  62914. };
  62915. serializationObject.bones.push(serializedBone);
  62916. if (bone.length) {
  62917. serializedBone.length = bone.length;
  62918. }
  62919. if (bone.animations && bone.animations.length > 0) {
  62920. serializedBone.animation = bone.animations[0].serialize();
  62921. }
  62922. serializationObject.ranges = [];
  62923. for (var name in this._ranges) {
  62924. var source = this._ranges[name];
  62925. if (!source) {
  62926. continue;
  62927. }
  62928. var range = {};
  62929. range.name = name;
  62930. range.from = source.from;
  62931. range.to = source.to;
  62932. serializationObject.ranges.push(range);
  62933. }
  62934. }
  62935. return serializationObject;
  62936. };
  62937. Skeleton.Parse = function (parsedSkeleton, scene) {
  62938. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  62939. if (parsedSkeleton.dimensionsAtRest) {
  62940. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  62941. }
  62942. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  62943. var index;
  62944. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  62945. var parsedBone = parsedSkeleton.bones[index];
  62946. var parentBone = null;
  62947. if (parsedBone.parentBoneIndex > -1) {
  62948. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  62949. }
  62950. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  62951. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  62952. if (parsedBone.length) {
  62953. bone.length = parsedBone.length;
  62954. }
  62955. if (parsedBone.animation) {
  62956. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  62957. }
  62958. }
  62959. // placed after bones, so createAnimationRange can cascade down
  62960. if (parsedSkeleton.ranges) {
  62961. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  62962. var data = parsedSkeleton.ranges[index];
  62963. skeleton.createAnimationRange(data.name, data.from, data.to);
  62964. }
  62965. }
  62966. return skeleton;
  62967. };
  62968. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  62969. if (forceUpdate === void 0) { forceUpdate = false; }
  62970. var renderId = this._scene.getRenderId();
  62971. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  62972. this.bones[0].computeAbsoluteTransforms();
  62973. this._lastAbsoluteTransformsUpdateId = renderId;
  62974. }
  62975. };
  62976. Skeleton.prototype.getPoseMatrix = function () {
  62977. var poseMatrix = null;
  62978. if (this._meshesWithPoseMatrix.length > 0) {
  62979. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  62980. }
  62981. return poseMatrix;
  62982. };
  62983. Skeleton.prototype.sortBones = function () {
  62984. var bones = new Array();
  62985. var visited = new Array(this.bones.length);
  62986. for (var index = 0; index < this.bones.length; index++) {
  62987. this._sortBones(index, bones, visited);
  62988. }
  62989. this.bones = bones;
  62990. };
  62991. Skeleton.prototype._sortBones = function (index, bones, visited) {
  62992. if (visited[index]) {
  62993. return;
  62994. }
  62995. visited[index] = true;
  62996. var bone = this.bones[index];
  62997. if (bone._index === undefined) {
  62998. bone._index = index;
  62999. }
  63000. var parentBone = bone.getParent();
  63001. if (parentBone) {
  63002. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  63003. }
  63004. bones.push(bone);
  63005. };
  63006. return Skeleton;
  63007. }());
  63008. BABYLON.Skeleton = Skeleton;
  63009. })(BABYLON || (BABYLON = {}));
  63010. //# sourceMappingURL=babylon.skeleton.js.map
  63011. var BABYLON;
  63012. (function (BABYLON) {
  63013. var SphericalPolynomial = /** @class */ (function () {
  63014. function SphericalPolynomial() {
  63015. this.x = BABYLON.Vector3.Zero();
  63016. this.y = BABYLON.Vector3.Zero();
  63017. this.z = BABYLON.Vector3.Zero();
  63018. this.xx = BABYLON.Vector3.Zero();
  63019. this.yy = BABYLON.Vector3.Zero();
  63020. this.zz = BABYLON.Vector3.Zero();
  63021. this.xy = BABYLON.Vector3.Zero();
  63022. this.yz = BABYLON.Vector3.Zero();
  63023. this.zx = BABYLON.Vector3.Zero();
  63024. }
  63025. SphericalPolynomial.prototype.addAmbient = function (color) {
  63026. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  63027. this.xx = this.xx.add(colorVector);
  63028. this.yy = this.yy.add(colorVector);
  63029. this.zz = this.zz.add(colorVector);
  63030. };
  63031. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  63032. var result = new SphericalPolynomial();
  63033. result.x = harmonics.L11.scale(1.02333);
  63034. result.y = harmonics.L1_1.scale(1.02333);
  63035. result.z = harmonics.L10.scale(1.02333);
  63036. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  63037. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  63038. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  63039. result.yz = harmonics.L2_1.scale(0.858086);
  63040. result.zx = harmonics.L21.scale(0.858086);
  63041. result.xy = harmonics.L2_2.scale(0.858086);
  63042. result.scale(1.0 / Math.PI);
  63043. return result;
  63044. };
  63045. SphericalPolynomial.prototype.scale = function (scale) {
  63046. this.x = this.x.scale(scale);
  63047. this.y = this.y.scale(scale);
  63048. this.z = this.z.scale(scale);
  63049. this.xx = this.xx.scale(scale);
  63050. this.yy = this.yy.scale(scale);
  63051. this.zz = this.zz.scale(scale);
  63052. this.yz = this.yz.scale(scale);
  63053. this.zx = this.zx.scale(scale);
  63054. this.xy = this.xy.scale(scale);
  63055. };
  63056. return SphericalPolynomial;
  63057. }());
  63058. BABYLON.SphericalPolynomial = SphericalPolynomial;
  63059. var SphericalHarmonics = /** @class */ (function () {
  63060. function SphericalHarmonics() {
  63061. this.L00 = BABYLON.Vector3.Zero();
  63062. this.L1_1 = BABYLON.Vector3.Zero();
  63063. this.L10 = BABYLON.Vector3.Zero();
  63064. this.L11 = BABYLON.Vector3.Zero();
  63065. this.L2_2 = BABYLON.Vector3.Zero();
  63066. this.L2_1 = BABYLON.Vector3.Zero();
  63067. this.L20 = BABYLON.Vector3.Zero();
  63068. this.L21 = BABYLON.Vector3.Zero();
  63069. this.L22 = BABYLON.Vector3.Zero();
  63070. }
  63071. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  63072. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  63073. var c = colorVector.scale(deltaSolidAngle);
  63074. this.L00 = this.L00.add(c.scale(0.282095));
  63075. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  63076. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  63077. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  63078. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  63079. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  63080. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  63081. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  63082. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  63083. };
  63084. SphericalHarmonics.prototype.scale = function (scale) {
  63085. this.L00 = this.L00.scale(scale);
  63086. this.L1_1 = this.L1_1.scale(scale);
  63087. this.L10 = this.L10.scale(scale);
  63088. this.L11 = this.L11.scale(scale);
  63089. this.L2_2 = this.L2_2.scale(scale);
  63090. this.L2_1 = this.L2_1.scale(scale);
  63091. this.L20 = this.L20.scale(scale);
  63092. this.L21 = this.L21.scale(scale);
  63093. this.L22 = this.L22.scale(scale);
  63094. };
  63095. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  63096. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  63097. //
  63098. // E_lm = A_l * L_lm
  63099. //
  63100. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  63101. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  63102. // the scaling factors are given in equation 9.
  63103. // Constant (Band 0)
  63104. this.L00 = this.L00.scale(3.141593);
  63105. // Linear (Band 1)
  63106. this.L1_1 = this.L1_1.scale(2.094395);
  63107. this.L10 = this.L10.scale(2.094395);
  63108. this.L11 = this.L11.scale(2.094395);
  63109. // Quadratic (Band 2)
  63110. this.L2_2 = this.L2_2.scale(0.785398);
  63111. this.L2_1 = this.L2_1.scale(0.785398);
  63112. this.L20 = this.L20.scale(0.785398);
  63113. this.L21 = this.L21.scale(0.785398);
  63114. this.L22 = this.L22.scale(0.785398);
  63115. };
  63116. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  63117. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  63118. // L = (1/pi) * E * rho
  63119. //
  63120. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  63121. this.scale(1.0 / Math.PI);
  63122. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  63123. // (The pixel shader must apply albedo after texture fetches, etc).
  63124. };
  63125. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  63126. var result = new SphericalHarmonics();
  63127. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  63128. result.L1_1 = polynomial.y.scale(0.977204);
  63129. result.L10 = polynomial.z.scale(0.977204);
  63130. result.L11 = polynomial.x.scale(0.977204);
  63131. result.L2_2 = polynomial.xy.scale(1.16538);
  63132. result.L2_1 = polynomial.yz.scale(1.16538);
  63133. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  63134. result.L21 = polynomial.zx.scale(1.16538);
  63135. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  63136. result.scale(Math.PI);
  63137. return result;
  63138. };
  63139. return SphericalHarmonics;
  63140. }());
  63141. BABYLON.SphericalHarmonics = SphericalHarmonics;
  63142. })(BABYLON || (BABYLON = {}));
  63143. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  63144. var BABYLON;
  63145. (function (BABYLON) {
  63146. var Internals;
  63147. (function (Internals) {
  63148. var FileFaceOrientation = /** @class */ (function () {
  63149. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  63150. this.name = name;
  63151. this.worldAxisForNormal = worldAxisForNormal;
  63152. this.worldAxisForFileX = worldAxisForFileX;
  63153. this.worldAxisForFileY = worldAxisForFileY;
  63154. }
  63155. return FileFaceOrientation;
  63156. }());
  63157. ;
  63158. /**
  63159. * Helper class dealing with the extraction of spherical polynomial dataArray
  63160. * from a cube map.
  63161. */
  63162. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  63163. function CubeMapToSphericalPolynomialTools() {
  63164. }
  63165. /**
  63166. * Converts a texture to the according Spherical Polynomial data.
  63167. * This extracts the first 3 orders only as they are the only one used in the lighting.
  63168. *
  63169. * @param texture The texture to extract the information from.
  63170. * @return The Spherical Polynomial data.
  63171. */
  63172. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  63173. if (!texture.isCube) {
  63174. // Only supports cube Textures currently.
  63175. return null;
  63176. }
  63177. var size = texture.getSize().width;
  63178. var right = texture.readPixels(0);
  63179. var left = texture.readPixels(1);
  63180. var up;
  63181. var down;
  63182. if (texture.isRenderTarget) {
  63183. up = texture.readPixels(3);
  63184. down = texture.readPixels(2);
  63185. }
  63186. else {
  63187. up = texture.readPixels(2);
  63188. down = texture.readPixels(3);
  63189. }
  63190. var front = texture.readPixels(4);
  63191. var back = texture.readPixels(5);
  63192. var gammaSpace = texture.gammaSpace;
  63193. // Always read as RGBA.
  63194. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  63195. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63196. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  63197. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63198. }
  63199. var cubeInfo = {
  63200. size: size,
  63201. right: right,
  63202. left: left,
  63203. up: up,
  63204. down: down,
  63205. front: front,
  63206. back: back,
  63207. format: format,
  63208. type: type,
  63209. gammaSpace: gammaSpace,
  63210. };
  63211. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  63212. };
  63213. /**
  63214. * Converts a cubemap to the according Spherical Polynomial data.
  63215. * This extracts the first 3 orders only as they are the only one used in the lighting.
  63216. *
  63217. * @param cubeInfo The Cube map to extract the information from.
  63218. * @return The Spherical Polynomial data.
  63219. */
  63220. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  63221. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  63222. var totalSolidAngle = 0.0;
  63223. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  63224. var du = 2.0 / cubeInfo.size;
  63225. var dv = du;
  63226. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  63227. var minUV = du * 0.5 - 1.0;
  63228. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  63229. var fileFace = this.FileFaces[faceIndex];
  63230. var dataArray = cubeInfo[fileFace.name];
  63231. var v = minUV;
  63232. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  63233. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  63234. // Because SP is still linear, so summation is fine in that basis.
  63235. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  63236. for (var y = 0; y < cubeInfo.size; y++) {
  63237. var u = minUV;
  63238. for (var x = 0; x < cubeInfo.size; x++) {
  63239. // World direction (not normalised)
  63240. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  63241. worldDirection.normalize();
  63242. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  63243. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  63244. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  63245. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  63246. // Handle Integer types.
  63247. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  63248. r /= 255;
  63249. g /= 255;
  63250. b /= 255;
  63251. }
  63252. // Handle Gamma space textures.
  63253. if (cubeInfo.gammaSpace) {
  63254. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  63255. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  63256. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  63257. }
  63258. var color = new BABYLON.Color3(r, g, b);
  63259. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  63260. totalSolidAngle += deltaSolidAngle;
  63261. u += du;
  63262. }
  63263. v += dv;
  63264. }
  63265. }
  63266. // Solid angle for entire sphere is 4*pi
  63267. var sphereSolidAngle = 4.0 * Math.PI;
  63268. // Adjust the solid angle to allow for how many faces we processed.
  63269. var facesProcessed = 6.0;
  63270. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  63271. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  63272. // This is needed because the numerical integration over the cube uses a
  63273. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  63274. // and also to compensate for accumulative error due to float precision in the summation.
  63275. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  63276. sphericalHarmonics.scale(correctionFactor);
  63277. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  63278. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  63279. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  63280. };
  63281. CubeMapToSphericalPolynomialTools.FileFaces = [
  63282. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  63283. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  63284. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  63285. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  63286. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  63287. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  63288. ];
  63289. return CubeMapToSphericalPolynomialTools;
  63290. }());
  63291. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  63292. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63293. })(BABYLON || (BABYLON = {}));
  63294. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  63295. var BABYLON;
  63296. (function (BABYLON) {
  63297. var Internals;
  63298. (function (Internals) {
  63299. /**
  63300. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  63301. */
  63302. var PanoramaToCubeMapTools = /** @class */ (function () {
  63303. function PanoramaToCubeMapTools() {
  63304. }
  63305. /**
  63306. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  63307. *
  63308. * @param float32Array The source data.
  63309. * @param inputWidth The width of the input panorama.
  63310. * @param inputhHeight The height of the input panorama.
  63311. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  63312. * @return The cubemap data
  63313. */
  63314. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  63315. if (!float32Array) {
  63316. throw "ConvertPanoramaToCubemap: input cannot be null";
  63317. }
  63318. if (float32Array.length != inputWidth * inputHeight * 3) {
  63319. throw "ConvertPanoramaToCubemap: input size is wrong";
  63320. }
  63321. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  63322. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  63323. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  63324. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  63325. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  63326. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  63327. return {
  63328. front: textureFront,
  63329. back: textureBack,
  63330. left: textureLeft,
  63331. right: textureRight,
  63332. up: textureUp,
  63333. down: textureDown,
  63334. size: size,
  63335. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  63336. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  63337. gammaSpace: false,
  63338. };
  63339. };
  63340. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  63341. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  63342. var textureArray = new Float32Array(buffer);
  63343. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  63344. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  63345. var dy = 1 / texSize;
  63346. var fy = 0;
  63347. for (var y = 0; y < texSize; y++) {
  63348. var xv1 = faceData[0];
  63349. var xv2 = faceData[2];
  63350. for (var x = 0; x < texSize; x++) {
  63351. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  63352. v.normalize();
  63353. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  63354. // 3 channels per pixels
  63355. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  63356. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  63357. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  63358. xv1 = xv1.add(rotDX1);
  63359. xv2 = xv2.add(rotDX2);
  63360. }
  63361. fy += dy;
  63362. }
  63363. return textureArray;
  63364. };
  63365. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  63366. var theta = Math.atan2(vDir.z, vDir.x);
  63367. var phi = Math.acos(vDir.y);
  63368. while (theta < -Math.PI)
  63369. theta += 2 * Math.PI;
  63370. while (theta > Math.PI)
  63371. theta -= 2 * Math.PI;
  63372. var dx = theta / Math.PI;
  63373. var dy = phi / Math.PI;
  63374. // recenter.
  63375. dx = dx * 0.5 + 0.5;
  63376. var px = Math.round(dx * inputWidth);
  63377. if (px < 0)
  63378. px = 0;
  63379. else if (px >= inputWidth)
  63380. px = inputWidth - 1;
  63381. var py = Math.round(dy * inputHeight);
  63382. if (py < 0)
  63383. py = 0;
  63384. else if (py >= inputHeight)
  63385. py = inputHeight - 1;
  63386. var inputY = (inputHeight - py - 1);
  63387. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  63388. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  63389. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  63390. return {
  63391. r: r,
  63392. g: g,
  63393. b: b
  63394. };
  63395. };
  63396. PanoramaToCubeMapTools.FACE_FRONT = [
  63397. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  63398. new BABYLON.Vector3(1.0, -1.0, -1.0),
  63399. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  63400. new BABYLON.Vector3(1.0, 1.0, -1.0)
  63401. ];
  63402. PanoramaToCubeMapTools.FACE_BACK = [
  63403. new BABYLON.Vector3(1.0, -1.0, 1.0),
  63404. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  63405. new BABYLON.Vector3(1.0, 1.0, 1.0),
  63406. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  63407. ];
  63408. PanoramaToCubeMapTools.FACE_RIGHT = [
  63409. new BABYLON.Vector3(1.0, -1.0, -1.0),
  63410. new BABYLON.Vector3(1.0, -1.0, 1.0),
  63411. new BABYLON.Vector3(1.0, 1.0, -1.0),
  63412. new BABYLON.Vector3(1.0, 1.0, 1.0)
  63413. ];
  63414. PanoramaToCubeMapTools.FACE_LEFT = [
  63415. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  63416. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  63417. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  63418. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  63419. ];
  63420. PanoramaToCubeMapTools.FACE_DOWN = [
  63421. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  63422. new BABYLON.Vector3(1.0, 1.0, -1.0),
  63423. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  63424. new BABYLON.Vector3(1.0, 1.0, 1.0)
  63425. ];
  63426. PanoramaToCubeMapTools.FACE_UP = [
  63427. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  63428. new BABYLON.Vector3(1.0, -1.0, 1.0),
  63429. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  63430. new BABYLON.Vector3(1.0, -1.0, -1.0)
  63431. ];
  63432. return PanoramaToCubeMapTools;
  63433. }());
  63434. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  63435. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63436. })(BABYLON || (BABYLON = {}));
  63437. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  63438. var BABYLON;
  63439. (function (BABYLON) {
  63440. var Internals;
  63441. (function (Internals) {
  63442. ;
  63443. /**
  63444. * This groups tools to convert HDR texture to native colors array.
  63445. */
  63446. var HDRTools = /** @class */ (function () {
  63447. function HDRTools() {
  63448. }
  63449. HDRTools.Ldexp = function (mantissa, exponent) {
  63450. if (exponent > 1023) {
  63451. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  63452. }
  63453. if (exponent < -1074) {
  63454. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  63455. }
  63456. return mantissa * Math.pow(2, exponent);
  63457. };
  63458. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  63459. if (exponent > 0) {
  63460. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  63461. float32array[index + 0] = red * exponent;
  63462. float32array[index + 1] = green * exponent;
  63463. float32array[index + 2] = blue * exponent;
  63464. }
  63465. else {
  63466. float32array[index + 0] = 0;
  63467. float32array[index + 1] = 0;
  63468. float32array[index + 2] = 0;
  63469. }
  63470. };
  63471. HDRTools.readStringLine = function (uint8array, startIndex) {
  63472. var line = "";
  63473. var character = "";
  63474. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  63475. character = String.fromCharCode(uint8array[i]);
  63476. if (character == "\n") {
  63477. break;
  63478. }
  63479. line += character;
  63480. }
  63481. return line;
  63482. };
  63483. /**
  63484. * Reads header information from an RGBE texture stored in a native array.
  63485. * More information on this format are available here:
  63486. * https://en.wikipedia.org/wiki/RGBE_image_format
  63487. *
  63488. * @param uint8array The binary file stored in native array.
  63489. * @return The header information.
  63490. */
  63491. HDRTools.RGBE_ReadHeader = function (uint8array) {
  63492. var height = 0;
  63493. var width = 0;
  63494. var line = this.readStringLine(uint8array, 0);
  63495. if (line[0] != '#' || line[1] != '?') {
  63496. throw "Bad HDR Format.";
  63497. }
  63498. var endOfHeader = false;
  63499. var findFormat = false;
  63500. var lineIndex = 0;
  63501. do {
  63502. lineIndex += (line.length + 1);
  63503. line = this.readStringLine(uint8array, lineIndex);
  63504. if (line == "FORMAT=32-bit_rle_rgbe") {
  63505. findFormat = true;
  63506. }
  63507. else if (line.length == 0) {
  63508. endOfHeader = true;
  63509. }
  63510. } while (!endOfHeader);
  63511. if (!findFormat) {
  63512. throw "HDR Bad header format, unsupported FORMAT";
  63513. }
  63514. lineIndex += (line.length + 1);
  63515. line = this.readStringLine(uint8array, lineIndex);
  63516. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  63517. var match = sizeRegexp.exec(line);
  63518. // TODO. Support +Y and -X if needed.
  63519. if (!match || match.length < 3) {
  63520. throw "HDR Bad header format, no size";
  63521. }
  63522. width = parseInt(match[2]);
  63523. height = parseInt(match[1]);
  63524. if (width < 8 || width > 0x7fff) {
  63525. throw "HDR Bad header format, unsupported size";
  63526. }
  63527. lineIndex += (line.length + 1);
  63528. return {
  63529. height: height,
  63530. width: width,
  63531. dataPosition: lineIndex
  63532. };
  63533. };
  63534. /**
  63535. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  63536. * This RGBE texture needs to store the information as a panorama.
  63537. *
  63538. * More information on this format are available here:
  63539. * https://en.wikipedia.org/wiki/RGBE_image_format
  63540. *
  63541. * @param buffer The binary file stored in an array buffer.
  63542. * @param size The expected size of the extracted cubemap.
  63543. * @return The Cube Map information.
  63544. */
  63545. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  63546. var uint8array = new Uint8Array(buffer);
  63547. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  63548. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  63549. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  63550. return cubeMapData;
  63551. };
  63552. /**
  63553. * Returns the pixels data extracted from an RGBE texture.
  63554. * This pixels will be stored left to right up to down in the R G B order in one array.
  63555. *
  63556. * More information on this format are available here:
  63557. * https://en.wikipedia.org/wiki/RGBE_image_format
  63558. *
  63559. * @param uint8array The binary file stored in an array buffer.
  63560. * @param hdrInfo The header information of the file.
  63561. * @return The pixels data in RGB right to left up to down order.
  63562. */
  63563. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  63564. // Keep for multi format supports.
  63565. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  63566. };
  63567. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  63568. var num_scanlines = hdrInfo.height;
  63569. var scanline_width = hdrInfo.width;
  63570. var a, b, c, d, count;
  63571. var dataIndex = hdrInfo.dataPosition;
  63572. var index = 0, endIndex = 0, i = 0;
  63573. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  63574. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  63575. // 3 channels of 4 bytes per pixel in float.
  63576. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  63577. var resultArray = new Float32Array(resultBuffer);
  63578. // read in each successive scanline
  63579. while (num_scanlines > 0) {
  63580. a = uint8array[dataIndex++];
  63581. b = uint8array[dataIndex++];
  63582. c = uint8array[dataIndex++];
  63583. d = uint8array[dataIndex++];
  63584. if (a != 2 || b != 2 || (c & 0x80)) {
  63585. // this file is not run length encoded
  63586. throw "HDR Bad header format, not RLE";
  63587. }
  63588. if (((c << 8) | d) != scanline_width) {
  63589. throw "HDR Bad header format, wrong scan line width";
  63590. }
  63591. index = 0;
  63592. // read each of the four channels for the scanline into the buffer
  63593. for (i = 0; i < 4; i++) {
  63594. endIndex = (i + 1) * scanline_width;
  63595. while (index < endIndex) {
  63596. a = uint8array[dataIndex++];
  63597. b = uint8array[dataIndex++];
  63598. if (a > 128) {
  63599. // a run of the same value
  63600. count = a - 128;
  63601. if ((count == 0) || (count > endIndex - index)) {
  63602. throw "HDR Bad Format, bad scanline data (run)";
  63603. }
  63604. while (count-- > 0) {
  63605. scanLineArray[index++] = b;
  63606. }
  63607. }
  63608. else {
  63609. // a non-run
  63610. count = a;
  63611. if ((count == 0) || (count > endIndex - index)) {
  63612. throw "HDR Bad Format, bad scanline data (non-run)";
  63613. }
  63614. scanLineArray[index++] = b;
  63615. if (--count > 0) {
  63616. for (var j = 0; j < count; j++) {
  63617. scanLineArray[index++] = uint8array[dataIndex++];
  63618. }
  63619. }
  63620. }
  63621. }
  63622. }
  63623. // now convert data from buffer into floats
  63624. for (i = 0; i < scanline_width; i++) {
  63625. a = scanLineArray[i];
  63626. b = scanLineArray[i + scanline_width];
  63627. c = scanLineArray[i + 2 * scanline_width];
  63628. d = scanLineArray[i + 3 * scanline_width];
  63629. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  63630. }
  63631. num_scanlines--;
  63632. }
  63633. return resultArray;
  63634. };
  63635. return HDRTools;
  63636. }());
  63637. Internals.HDRTools = HDRTools;
  63638. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63639. })(BABYLON || (BABYLON = {}));
  63640. //# sourceMappingURL=babylon.hdr.js.map
  63641. var BABYLON;
  63642. (function (BABYLON) {
  63643. /**
  63644. * This represents a texture coming from an HDR input.
  63645. *
  63646. * The only supported format is currently panorama picture stored in RGBE format.
  63647. * Example of such files can be found on HDRLib: http://hdrlib.com/
  63648. */
  63649. var HDRCubeTexture = /** @class */ (function (_super) {
  63650. __extends(HDRCubeTexture, _super);
  63651. /**
  63652. * Instantiates an HDRTexture from the following parameters.
  63653. *
  63654. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  63655. * @param scene The scene the texture will be used in
  63656. * @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.
  63657. * @param noMipmap Forces to not generate the mipmap if true
  63658. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  63659. * @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)
  63660. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  63661. */
  63662. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  63663. if (noMipmap === void 0) { noMipmap = false; }
  63664. if (generateHarmonics === void 0) { generateHarmonics = true; }
  63665. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  63666. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  63667. if (onLoad === void 0) { onLoad = null; }
  63668. if (onError === void 0) { onError = null; }
  63669. var _this = _super.call(this, scene) || this;
  63670. _this._useInGammaSpace = false;
  63671. _this._generateHarmonics = true;
  63672. _this._isBABYLONPreprocessed = false;
  63673. _this._onLoad = null;
  63674. _this._onError = null;
  63675. /**
  63676. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  63677. */
  63678. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63679. /**
  63680. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  63681. * This is usefull at run time to apply the good shader.
  63682. */
  63683. _this.isPMREM = false;
  63684. _this._isBlocking = true;
  63685. if (!url) {
  63686. return _this;
  63687. }
  63688. _this.name = url;
  63689. _this.url = url;
  63690. _this.hasAlpha = false;
  63691. _this.isCube = true;
  63692. _this._textureMatrix = BABYLON.Matrix.Identity();
  63693. _this._onLoad = onLoad;
  63694. _this._onError = onError;
  63695. _this.gammaSpace = false;
  63696. var caps = scene.getEngine().getCaps();
  63697. if (size) {
  63698. _this._isBABYLONPreprocessed = false;
  63699. _this._noMipmap = noMipmap;
  63700. _this._size = size;
  63701. _this._useInGammaSpace = useInGammaSpace;
  63702. _this._usePMREMGenerator = usePMREMGenerator &&
  63703. caps.textureLOD &&
  63704. caps.textureFloat &&
  63705. !_this._useInGammaSpace;
  63706. }
  63707. else {
  63708. _this._isBABYLONPreprocessed = true;
  63709. _this._noMipmap = false;
  63710. _this._useInGammaSpace = false;
  63711. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  63712. !_this._useInGammaSpace;
  63713. }
  63714. _this.isPMREM = _this._usePMREMGenerator;
  63715. _this._texture = _this._getFromCache(url, _this._noMipmap);
  63716. if (!_this._texture) {
  63717. if (!scene.useDelayedTextureLoading) {
  63718. _this.loadTexture();
  63719. }
  63720. else {
  63721. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63722. }
  63723. }
  63724. return _this;
  63725. }
  63726. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  63727. /**
  63728. * Gets wether or not the texture is blocking during loading.
  63729. */
  63730. get: function () {
  63731. return this._isBlocking;
  63732. },
  63733. /**
  63734. * Sets wether or not the texture is blocking during loading.
  63735. */
  63736. set: function (value) {
  63737. this._isBlocking = value;
  63738. },
  63739. enumerable: true,
  63740. configurable: true
  63741. });
  63742. /**
  63743. * Occurs when the file is a preprocessed .babylon.hdr file.
  63744. */
  63745. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  63746. var _this = this;
  63747. var mipLevels = 0;
  63748. var floatArrayView = null;
  63749. var scene = this.getScene();
  63750. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  63751. var mips = new Array();
  63752. if (!floatArrayView) {
  63753. return mips;
  63754. }
  63755. var startIndex = 30;
  63756. for (var level = 0; level < mipLevels; level++) {
  63757. mips.push([]);
  63758. // Fill each pixel of the mip level.
  63759. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  63760. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  63761. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  63762. mips[level].push(faceData);
  63763. startIndex += faceSize;
  63764. }
  63765. }
  63766. return mips;
  63767. } : null;
  63768. var callback = function (buffer) {
  63769. var scene = _this.getScene();
  63770. if (!scene) {
  63771. return null;
  63772. }
  63773. // Create Native Array Views
  63774. var intArrayView = new Int32Array(buffer);
  63775. floatArrayView = new Float32Array(buffer);
  63776. // Fill header.
  63777. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  63778. _this._size = intArrayView[1]; // CubeMap max mip face size.
  63779. // Update Texture Information.
  63780. if (!_this._texture) {
  63781. return null;
  63782. }
  63783. _this._texture.updateSize(_this._size, _this._size);
  63784. // Fill polynomial information.
  63785. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  63786. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  63787. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  63788. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  63789. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  63790. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  63791. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  63792. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  63793. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  63794. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  63795. _this.sphericalPolynomial = sphericalPolynomial;
  63796. // Fill pixel data.
  63797. mipLevels = intArrayView[29]; // Number of mip levels.
  63798. var startIndex = 30;
  63799. var data = [];
  63800. var faceSize = Math.pow(_this._size, 2) * 3;
  63801. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  63802. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  63803. startIndex += faceSize;
  63804. }
  63805. var results = [];
  63806. var byteArray = null;
  63807. // Push each faces.
  63808. for (var k = 0; k < 6; k++) {
  63809. var dataFace = null;
  63810. // To be deprecated.
  63811. if (version === 1) {
  63812. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  63813. dataFace = data[j];
  63814. }
  63815. // If special cases.
  63816. if (!mipmapGenerator && dataFace) {
  63817. if (!scene.getEngine().getCaps().textureFloat) {
  63818. // 3 channels of 1 bytes per pixel in bytes.
  63819. var byteBuffer = new ArrayBuffer(faceSize);
  63820. byteArray = new Uint8Array(byteBuffer);
  63821. }
  63822. for (var i = 0; i < _this._size * _this._size; i++) {
  63823. // Put in gamma space if requested.
  63824. if (_this._useInGammaSpace) {
  63825. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  63826. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  63827. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  63828. }
  63829. // Convert to int texture for fallback.
  63830. if (byteArray) {
  63831. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  63832. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  63833. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  63834. // May use luminance instead if the result is not accurate.
  63835. var max = Math.max(Math.max(r, g), b);
  63836. if (max > 255) {
  63837. var scale = 255 / max;
  63838. r *= scale;
  63839. g *= scale;
  63840. b *= scale;
  63841. }
  63842. byteArray[(i * 3) + 0] = r;
  63843. byteArray[(i * 3) + 1] = g;
  63844. byteArray[(i * 3) + 2] = b;
  63845. }
  63846. }
  63847. }
  63848. // Fill the array accordingly.
  63849. if (byteArray) {
  63850. results.push(byteArray);
  63851. }
  63852. else {
  63853. results.push(dataFace);
  63854. }
  63855. }
  63856. return results;
  63857. };
  63858. if (scene) {
  63859. 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);
  63860. }
  63861. };
  63862. /**
  63863. * Occurs when the file is raw .hdr file.
  63864. */
  63865. HDRCubeTexture.prototype.loadHDRTexture = function () {
  63866. var _this = this;
  63867. var callback = function (buffer) {
  63868. var scene = _this.getScene();
  63869. if (!scene) {
  63870. return null;
  63871. }
  63872. // Extract the raw linear data.
  63873. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  63874. // Generate harmonics if needed.
  63875. if (_this._generateHarmonics) {
  63876. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  63877. _this.sphericalPolynomial = sphericalPolynomial;
  63878. }
  63879. var results = [];
  63880. var byteArray = null;
  63881. // Push each faces.
  63882. for (var j = 0; j < 6; j++) {
  63883. // Create uintarray fallback.
  63884. if (!scene.getEngine().getCaps().textureFloat) {
  63885. // 3 channels of 1 bytes per pixel in bytes.
  63886. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  63887. byteArray = new Uint8Array(byteBuffer);
  63888. }
  63889. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  63890. // If special cases.
  63891. if (_this._useInGammaSpace || byteArray) {
  63892. for (var i = 0; i < _this._size * _this._size; i++) {
  63893. // Put in gamma space if requested.
  63894. if (_this._useInGammaSpace) {
  63895. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  63896. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  63897. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  63898. }
  63899. // Convert to int texture for fallback.
  63900. if (byteArray) {
  63901. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  63902. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  63903. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  63904. // May use luminance instead if the result is not accurate.
  63905. var max = Math.max(Math.max(r, g), b);
  63906. if (max > 255) {
  63907. var scale = 255 / max;
  63908. r *= scale;
  63909. g *= scale;
  63910. b *= scale;
  63911. }
  63912. byteArray[(i * 3) + 0] = r;
  63913. byteArray[(i * 3) + 1] = g;
  63914. byteArray[(i * 3) + 2] = b;
  63915. }
  63916. }
  63917. }
  63918. if (byteArray) {
  63919. results.push(byteArray);
  63920. }
  63921. else {
  63922. results.push(dataFace);
  63923. }
  63924. }
  63925. return results;
  63926. };
  63927. var mipmapGenerator = null;
  63928. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  63929. // if (!this._noMipmap &&
  63930. // this._usePMREMGenerator) {
  63931. // mipmapGenerator = (data: ArrayBufferView[]) => {
  63932. // // Custom setup of the generator matching with the PBR shader values.
  63933. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  63934. // this._size,
  63935. // this._size,
  63936. // 0,
  63937. // 3,
  63938. // this.getScene().getEngine().getCaps().textureFloat,
  63939. // 2048,
  63940. // 0.25,
  63941. // false,
  63942. // true);
  63943. // return generator.filterCubeMap();
  63944. // };
  63945. // }
  63946. var scene = this.getScene();
  63947. if (scene) {
  63948. 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);
  63949. }
  63950. };
  63951. /**
  63952. * Starts the loading process of the texture.
  63953. */
  63954. HDRCubeTexture.prototype.loadTexture = function () {
  63955. if (this._isBABYLONPreprocessed) {
  63956. this.loadBabylonTexture();
  63957. }
  63958. else {
  63959. this.loadHDRTexture();
  63960. }
  63961. };
  63962. HDRCubeTexture.prototype.clone = function () {
  63963. var scene = this.getScene();
  63964. if (!scene) {
  63965. return this;
  63966. }
  63967. var size = (this._isBABYLONPreprocessed ? null : this._size);
  63968. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  63969. // Base texture
  63970. newTexture.level = this.level;
  63971. newTexture.wrapU = this.wrapU;
  63972. newTexture.wrapV = this.wrapV;
  63973. newTexture.coordinatesIndex = this.coordinatesIndex;
  63974. newTexture.coordinatesMode = this.coordinatesMode;
  63975. return newTexture;
  63976. };
  63977. // Methods
  63978. HDRCubeTexture.prototype.delayLoad = function () {
  63979. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63980. return;
  63981. }
  63982. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63983. this._texture = this._getFromCache(this.url, this._noMipmap);
  63984. if (!this._texture) {
  63985. this.loadTexture();
  63986. }
  63987. };
  63988. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  63989. return this._textureMatrix;
  63990. };
  63991. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63992. this._textureMatrix = value;
  63993. };
  63994. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63995. var texture = null;
  63996. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  63997. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  63998. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  63999. texture.name = parsedTexture.name;
  64000. texture.hasAlpha = parsedTexture.hasAlpha;
  64001. texture.level = parsedTexture.level;
  64002. texture.coordinatesMode = parsedTexture.coordinatesMode;
  64003. texture.isBlocking = parsedTexture.isBlocking;
  64004. }
  64005. return texture;
  64006. };
  64007. HDRCubeTexture.prototype.serialize = function () {
  64008. if (!this.name) {
  64009. return null;
  64010. }
  64011. var serializationObject = {};
  64012. serializationObject.name = this.name;
  64013. serializationObject.hasAlpha = this.hasAlpha;
  64014. serializationObject.isCube = true;
  64015. serializationObject.level = this.level;
  64016. serializationObject.size = this._size;
  64017. serializationObject.coordinatesMode = this.coordinatesMode;
  64018. serializationObject.useInGammaSpace = this._useInGammaSpace;
  64019. serializationObject.generateHarmonics = this._generateHarmonics;
  64020. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  64021. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  64022. serializationObject.customType = "BABYLON.HDRCubeTexture";
  64023. serializationObject.noMipmap = this._noMipmap;
  64024. serializationObject.isBlocking = this._isBlocking;
  64025. return serializationObject;
  64026. };
  64027. /**
  64028. * Saves as a file the data contained in the texture in a binary format.
  64029. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  64030. * as the spherical used in the lighting.
  64031. * @param url The HDR file url.
  64032. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  64033. * @param onError Method called if any error happens during download.
  64034. * @return The packed binary data.
  64035. */
  64036. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  64037. if (onError === void 0) { onError = null; }
  64038. var callback = function (buffer) {
  64039. var data = new Blob([buffer], { type: 'application/octet-stream' });
  64040. // Returns a URL you can use as a href.
  64041. var objUrl = window.URL.createObjectURL(data);
  64042. // Simulates a link to it and click to dowload.
  64043. var a = document.createElement("a");
  64044. document.body.appendChild(a);
  64045. a.style.display = "none";
  64046. a.href = objUrl;
  64047. a.download = "envmap.babylon.hdr";
  64048. a.click();
  64049. };
  64050. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  64051. };
  64052. /**
  64053. * Serializes the data contained in the texture in a binary format.
  64054. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  64055. * as the spherical used in the lighting.
  64056. * @param url The HDR file url.
  64057. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  64058. * @param onError Method called if any error happens during download.
  64059. * @return The packed binary data.
  64060. */
  64061. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  64062. if (onError === void 0) { onError = null; }
  64063. // Needs the url tho create the texture.
  64064. if (!url) {
  64065. return;
  64066. }
  64067. // Check Power of two size.
  64068. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  64069. return;
  64070. }
  64071. // Coming Back in 3.x.
  64072. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  64073. };
  64074. HDRCubeTexture._facesMapping = [
  64075. "right",
  64076. "left",
  64077. "up",
  64078. "down",
  64079. "front",
  64080. "back"
  64081. ];
  64082. return HDRCubeTexture;
  64083. }(BABYLON.BaseTexture));
  64084. BABYLON.HDRCubeTexture = HDRCubeTexture;
  64085. })(BABYLON || (BABYLON = {}));
  64086. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  64087. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  64088. // Huge respect for a such great lib.
  64089. // Earcut license:
  64090. // Copyright (c) 2016, Mapbox
  64091. //
  64092. // Permission to use, copy, modify, and/or distribute this software for any purpose
  64093. // with or without fee is hereby granted, provided that the above copyright notice
  64094. // and this permission notice appear in all copies.
  64095. //
  64096. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  64097. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  64098. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  64099. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  64100. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  64101. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  64102. // THIS SOFTWARE.
  64103. var Earcut;
  64104. (function (Earcut) {
  64105. /**
  64106. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  64107. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  64108. * @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).
  64109. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  64110. */
  64111. function earcut(data, holeIndices, dim) {
  64112. dim = dim || 2;
  64113. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  64114. if (!outerNode)
  64115. return triangles;
  64116. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  64117. if (hasHoles)
  64118. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  64119. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  64120. if (data.length > 80 * dim) {
  64121. minX = maxX = data[0];
  64122. minY = maxY = data[1];
  64123. for (var i = dim; i < outerLen; i += dim) {
  64124. x = data[i];
  64125. y = data[i + 1];
  64126. if (x < minX)
  64127. minX = x;
  64128. if (y < minY)
  64129. minY = y;
  64130. if (x > maxX)
  64131. maxX = x;
  64132. if (y > maxY)
  64133. maxY = y;
  64134. }
  64135. // minX, minY and size are later used to transform coords into integers for z-order calculation
  64136. size = Math.max(maxX - minX, maxY - minY);
  64137. }
  64138. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  64139. return triangles;
  64140. }
  64141. Earcut.earcut = earcut;
  64142. var Node = /** @class */ (function () {
  64143. function Node(i, x, y) {
  64144. this.i = i;
  64145. this.x = x;
  64146. this.y = y;
  64147. this.prev = null;
  64148. this.next = null;
  64149. this.z = null;
  64150. this.prevZ = null;
  64151. this.nextZ = null;
  64152. this.steiner = false;
  64153. }
  64154. return Node;
  64155. }());
  64156. // create a circular doubly linked list from polygon points in the specified winding order
  64157. function linkedList(data, start, end, dim, clockwise) {
  64158. var i, last = null;
  64159. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  64160. for (i = start; i < end; i += dim)
  64161. last = insertNode(i, data[i], data[i + 1], last);
  64162. }
  64163. else {
  64164. for (i = end - dim; i >= start; i -= dim)
  64165. last = insertNode(i, data[i], data[i + 1], last);
  64166. }
  64167. if (last && equals(last, last.next)) {
  64168. removeNode(last);
  64169. last = last.next;
  64170. }
  64171. return last;
  64172. }
  64173. // eliminate colinear or duplicate points
  64174. function filterPoints(start, end) {
  64175. if (!start)
  64176. return start;
  64177. if (!end)
  64178. end = start;
  64179. var p = start, again;
  64180. do {
  64181. again = false;
  64182. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  64183. removeNode(p);
  64184. p = end = p.prev;
  64185. if (p === p.next)
  64186. return undefined;
  64187. again = true;
  64188. }
  64189. else {
  64190. p = p.next;
  64191. }
  64192. } while (again || p !== end);
  64193. return end;
  64194. }
  64195. // main ear slicing loop which triangulates a polygon (given as a linked list)
  64196. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  64197. if (!ear)
  64198. return;
  64199. // interlink polygon nodes in z-order
  64200. if (!pass && size)
  64201. indexCurve(ear, minX, minY, size);
  64202. var stop = ear, prev, next;
  64203. // iterate through ears, slicing them one by one
  64204. while (ear.prev !== ear.next) {
  64205. prev = ear.prev;
  64206. next = ear.next;
  64207. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  64208. // cut off the triangle
  64209. triangles.push(prev.i / dim);
  64210. triangles.push(ear.i / dim);
  64211. triangles.push(next.i / dim);
  64212. removeNode(ear);
  64213. // skipping the next vertice leads to less sliver triangles
  64214. ear = next.next;
  64215. stop = next.next;
  64216. continue;
  64217. }
  64218. ear = next;
  64219. // if we looped through the whole remaining polygon and can't find any more ears
  64220. if (ear === stop) {
  64221. // try filtering points and slicing again
  64222. if (!pass) {
  64223. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  64224. // if this didn't work, try curing all small self-intersections locally
  64225. }
  64226. else if (pass === 1) {
  64227. ear = cureLocalIntersections(ear, triangles, dim);
  64228. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  64229. // as a last resort, try splitting the remaining polygon into two
  64230. }
  64231. else if (pass === 2) {
  64232. splitEarcut(ear, triangles, dim, minX, minY, size);
  64233. }
  64234. break;
  64235. }
  64236. }
  64237. }
  64238. // check whether a polygon node forms a valid ear with adjacent nodes
  64239. function isEar(ear) {
  64240. var a = ear.prev, b = ear, c = ear.next;
  64241. if (area(a, b, c) >= 0)
  64242. return false; // reflex, can't be an ear
  64243. // now make sure we don't have other points inside the potential ear
  64244. var p = ear.next.next;
  64245. while (p !== ear.prev) {
  64246. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  64247. area(p.prev, p, p.next) >= 0)
  64248. return false;
  64249. p = p.next;
  64250. }
  64251. return true;
  64252. }
  64253. function isEarHashed(ear, minX, minY, size) {
  64254. var a = ear.prev, b = ear, c = ear.next;
  64255. if (area(a, b, c) >= 0)
  64256. return false; // reflex, can't be an ear
  64257. // triangle bbox; min & max are calculated like this for speed
  64258. 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);
  64259. // z-order range for the current triangle bbox;
  64260. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  64261. // first look for points inside the triangle in increasing z-order
  64262. var p = ear.nextZ;
  64263. while (p && p.z <= maxZ) {
  64264. if (p !== ear.prev &&
  64265. p !== ear.next &&
  64266. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  64267. area(p.prev, p, p.next) >= 0)
  64268. return false;
  64269. p = p.nextZ;
  64270. }
  64271. // then look for points in decreasing z-order
  64272. p = ear.prevZ;
  64273. while (p && p.z >= minZ) {
  64274. if (p !== ear.prev &&
  64275. p !== ear.next &&
  64276. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  64277. area(p.prev, p, p.next) >= 0)
  64278. return false;
  64279. p = p.prevZ;
  64280. }
  64281. return true;
  64282. }
  64283. // go through all polygon nodes and cure small local self-intersections
  64284. function cureLocalIntersections(start, triangles, dim) {
  64285. var p = start;
  64286. do {
  64287. var a = p.prev, b = p.next.next;
  64288. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  64289. triangles.push(a.i / dim);
  64290. triangles.push(p.i / dim);
  64291. triangles.push(b.i / dim);
  64292. // remove two nodes involved
  64293. removeNode(p);
  64294. removeNode(p.next);
  64295. p = start = b;
  64296. }
  64297. p = p.next;
  64298. } while (p !== start);
  64299. return p;
  64300. }
  64301. // try splitting polygon into two and triangulate them independently
  64302. function splitEarcut(start, triangles, dim, minX, minY, size) {
  64303. // look for a valid diagonal that divides the polygon into two
  64304. var a = start;
  64305. do {
  64306. var b = a.next.next;
  64307. while (b !== a.prev) {
  64308. if (a.i !== b.i && isValidDiagonal(a, b)) {
  64309. // split the polygon in two by the diagonal
  64310. var c = splitPolygon(a, b);
  64311. // filter colinear points around the cuts
  64312. a = filterPoints(a, a.next);
  64313. c = filterPoints(c, c.next);
  64314. // run earcut on each half
  64315. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  64316. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  64317. return;
  64318. }
  64319. b = b.next;
  64320. }
  64321. a = a.next;
  64322. } while (a !== start);
  64323. }
  64324. // link every hole into the outer loop, producing a single-ring polygon without holes
  64325. function eliminateHoles(data, holeIndices, outerNode, dim) {
  64326. var queue = [], i, len, start, end, list;
  64327. for (i = 0, len = holeIndices.length; i < len; i++) {
  64328. start = holeIndices[i] * dim;
  64329. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  64330. list = linkedList(data, start, end, dim, false);
  64331. if (list === list.next)
  64332. list.steiner = true;
  64333. queue.push(getLeftmost(list));
  64334. }
  64335. queue.sort(compareX);
  64336. // process holes from left to right
  64337. for (i = 0; i < queue.length; i++) {
  64338. eliminateHole(queue[i], outerNode);
  64339. outerNode = filterPoints(outerNode, outerNode.next);
  64340. }
  64341. return outerNode;
  64342. }
  64343. function compareX(a, b) {
  64344. return a.x - b.x;
  64345. }
  64346. // find a bridge between vertices that connects hole with an outer ring and and link it
  64347. function eliminateHole(hole, outerNode) {
  64348. outerNode = findHoleBridge(hole, outerNode);
  64349. if (outerNode) {
  64350. var b = splitPolygon(outerNode, hole);
  64351. filterPoints(b, b.next);
  64352. }
  64353. }
  64354. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  64355. function findHoleBridge(hole, outerNode) {
  64356. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  64357. // find a segment intersected by a ray from the hole's leftmost point to the left;
  64358. // segment's endpoint with lesser x will be potential connection point
  64359. do {
  64360. if (hy <= p.y && hy >= p.next.y) {
  64361. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  64362. if (x <= hx && x > qx) {
  64363. qx = x;
  64364. if (x === hx) {
  64365. if (hy === p.y)
  64366. return p;
  64367. if (hy === p.next.y)
  64368. return p.next;
  64369. }
  64370. m = p.x < p.next.x ? p : p.next;
  64371. }
  64372. }
  64373. p = p.next;
  64374. } while (p !== outerNode);
  64375. if (!m)
  64376. return null;
  64377. if (hx === qx)
  64378. return m.prev; // hole touches outer segment; pick lower endpoint
  64379. // look for points inside the triangle of hole point, segment intersection and endpoint;
  64380. // if there are no points found, we have a valid connection;
  64381. // otherwise choose the point of the minimum angle with the ray as connection point
  64382. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  64383. p = m.next;
  64384. while (p !== stop) {
  64385. if (hx >= p.x &&
  64386. p.x >= mx &&
  64387. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  64388. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  64389. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  64390. m = p;
  64391. tanMin = tan;
  64392. }
  64393. }
  64394. p = p.next;
  64395. }
  64396. return m;
  64397. }
  64398. // interlink polygon nodes in z-order
  64399. function indexCurve(start, minX, minY, size) {
  64400. var p = start;
  64401. do {
  64402. if (p.z === null)
  64403. p.z = zOrder(p.x, p.y, minX, minY, size);
  64404. p.prevZ = p.prev;
  64405. p.nextZ = p.next;
  64406. p = p.next;
  64407. } while (p !== start);
  64408. p.prevZ.nextZ = null;
  64409. p.prevZ = null;
  64410. sortLinked(p);
  64411. }
  64412. // Simon Tatham's linked list merge sort algorithm
  64413. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  64414. function sortLinked(list) {
  64415. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  64416. do {
  64417. p = list;
  64418. list = null;
  64419. tail = null;
  64420. numMerges = 0;
  64421. while (p) {
  64422. numMerges++;
  64423. q = p;
  64424. pSize = 0;
  64425. for (i = 0; i < inSize; i++) {
  64426. pSize++;
  64427. q = q.nextZ;
  64428. if (!q)
  64429. break;
  64430. }
  64431. qSize = inSize;
  64432. while (pSize > 0 || (qSize > 0 && q)) {
  64433. if (pSize === 0) {
  64434. e = q;
  64435. q = q.nextZ;
  64436. qSize--;
  64437. }
  64438. else if (qSize === 0 || !q) {
  64439. e = p;
  64440. p = p.nextZ;
  64441. pSize--;
  64442. }
  64443. else if (p.z <= q.z) {
  64444. e = p;
  64445. p = p.nextZ;
  64446. pSize--;
  64447. }
  64448. else {
  64449. e = q;
  64450. q = q.nextZ;
  64451. qSize--;
  64452. }
  64453. if (tail)
  64454. tail.nextZ = e;
  64455. else
  64456. list = e;
  64457. e.prevZ = tail;
  64458. tail = e;
  64459. }
  64460. p = q;
  64461. }
  64462. tail.nextZ = null;
  64463. inSize *= 2;
  64464. } while (numMerges > 1);
  64465. return list;
  64466. }
  64467. // z-order of a point given coords and size of the data bounding box
  64468. function zOrder(x, y, minX, minY, size) {
  64469. // coords are transformed into non-negative 15-bit integer range
  64470. x = 32767 * (x - minX) / size;
  64471. y = 32767 * (y - minY) / size;
  64472. x = (x | (x << 8)) & 0x00FF00FF;
  64473. x = (x | (x << 4)) & 0x0F0F0F0F;
  64474. x = (x | (x << 2)) & 0x33333333;
  64475. x = (x | (x << 1)) & 0x55555555;
  64476. y = (y | (y << 8)) & 0x00FF00FF;
  64477. y = (y | (y << 4)) & 0x0F0F0F0F;
  64478. y = (y | (y << 2)) & 0x33333333;
  64479. y = (y | (y << 1)) & 0x55555555;
  64480. return x | (y << 1);
  64481. }
  64482. // find the leftmost node of a polygon ring
  64483. function getLeftmost(start) {
  64484. var p = start, leftmost = start;
  64485. do {
  64486. if (p.x < leftmost.x)
  64487. leftmost = p;
  64488. p = p.next;
  64489. } while (p !== start);
  64490. return leftmost;
  64491. }
  64492. // check if a point lies within a convex triangle
  64493. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  64494. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  64495. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  64496. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  64497. }
  64498. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  64499. function isValidDiagonal(a, b) {
  64500. return a.next.i !== b.i &&
  64501. a.prev.i !== b.i &&
  64502. !intersectsPolygon(a, b) &&
  64503. locallyInside(a, b) &&
  64504. locallyInside(b, a) &&
  64505. middleInside(a, b);
  64506. }
  64507. // signed area of a triangle
  64508. function area(p, q, r) {
  64509. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  64510. }
  64511. // check if two points are equal
  64512. function equals(p1, p2) {
  64513. return p1.x === p2.x && p1.y === p2.y;
  64514. }
  64515. // check if two segments intersect
  64516. function intersects(p1, q1, p2, q2) {
  64517. if ((equals(p1, q1) && equals(p2, q2)) ||
  64518. (equals(p1, q2) && equals(p2, q1)))
  64519. return true;
  64520. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  64521. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  64522. }
  64523. // check if a polygon diagonal intersects any polygon segments
  64524. function intersectsPolygon(a, b) {
  64525. var p = a;
  64526. do {
  64527. if (p.i !== a.i &&
  64528. p.next.i !== a.i &&
  64529. p.i !== b.i &&
  64530. p.next.i !== b.i &&
  64531. intersects(p, p.next, a, b))
  64532. return true;
  64533. p = p.next;
  64534. } while (p !== a);
  64535. return false;
  64536. }
  64537. // check if a polygon diagonal is locally inside the polygon
  64538. function locallyInside(a, b) {
  64539. return area(a.prev, a, a.next) < 0
  64540. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  64541. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  64542. }
  64543. // check if the middle point of a polygon diagonal is inside the polygon
  64544. function middleInside(a, b) {
  64545. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  64546. do {
  64547. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  64548. inside = !inside;
  64549. p = p.next;
  64550. } while (p !== a);
  64551. return inside;
  64552. }
  64553. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  64554. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  64555. function splitPolygon(a, b) {
  64556. 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;
  64557. a.next = b;
  64558. b.prev = a;
  64559. a2.next = an;
  64560. an.prev = a2;
  64561. b2.next = a2;
  64562. a2.prev = b2;
  64563. bp.next = b2;
  64564. b2.prev = bp;
  64565. return b2;
  64566. }
  64567. // create a node and optionally link it with previous one (in a circular doubly linked list)
  64568. function insertNode(i, x, y, last) {
  64569. var p = new Node(i, x, y);
  64570. if (!last) {
  64571. p.prev = p;
  64572. p.next = p;
  64573. }
  64574. else {
  64575. p.next = last.next;
  64576. p.prev = last;
  64577. last.next.prev = p;
  64578. last.next = p;
  64579. }
  64580. return p;
  64581. }
  64582. function removeNode(p) {
  64583. p.next.prev = p.prev;
  64584. p.prev.next = p.next;
  64585. if (p.prevZ)
  64586. p.prevZ.nextZ = p.nextZ;
  64587. if (p.nextZ)
  64588. p.nextZ.prevZ = p.prevZ;
  64589. }
  64590. /**
  64591. * return a percentage difference between the polygon area and its triangulation area;
  64592. * used to verify correctness of triangulation
  64593. */
  64594. function deviation(data, holeIndices, dim, triangles) {
  64595. var hasHoles = holeIndices && holeIndices.length;
  64596. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  64597. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  64598. if (hasHoles) {
  64599. for (var i = 0, len = holeIndices.length; i < len; i++) {
  64600. var start = holeIndices[i] * dim;
  64601. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  64602. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  64603. }
  64604. }
  64605. var trianglesArea = 0;
  64606. for (i = 0; i < triangles.length; i += 3) {
  64607. var a = triangles[i] * dim;
  64608. var b = triangles[i + 1] * dim;
  64609. var c = triangles[i + 2] * dim;
  64610. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  64611. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  64612. }
  64613. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  64614. }
  64615. Earcut.deviation = deviation;
  64616. ;
  64617. function signedArea(data, start, end, dim) {
  64618. var sum = 0;
  64619. for (var i = start, j = end - dim; i < end; i += dim) {
  64620. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  64621. j = i;
  64622. }
  64623. return sum;
  64624. }
  64625. /**
  64626. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  64627. */
  64628. function flatten(data) {
  64629. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  64630. for (var i = 0; i < data.length; i++) {
  64631. for (var j = 0; j < data[i].length; j++) {
  64632. for (var d = 0; d < dim; d++)
  64633. result.vertices.push(data[i][j][d]);
  64634. }
  64635. if (i > 0) {
  64636. holeIndex += data[i - 1].length;
  64637. result.holes.push(holeIndex);
  64638. }
  64639. }
  64640. return result;
  64641. }
  64642. Earcut.flatten = flatten;
  64643. ;
  64644. })(Earcut || (Earcut = {}));
  64645. //# sourceMappingURL=babylon.earcut.js.map
  64646. var BABYLON;
  64647. (function (BABYLON) {
  64648. var IndexedVector2 = /** @class */ (function (_super) {
  64649. __extends(IndexedVector2, _super);
  64650. function IndexedVector2(original, index) {
  64651. var _this = _super.call(this, original.x, original.y) || this;
  64652. _this.index = index;
  64653. return _this;
  64654. }
  64655. return IndexedVector2;
  64656. }(BABYLON.Vector2));
  64657. var PolygonPoints = /** @class */ (function () {
  64658. function PolygonPoints() {
  64659. this.elements = new Array();
  64660. }
  64661. PolygonPoints.prototype.add = function (originalPoints) {
  64662. var _this = this;
  64663. var result = new Array();
  64664. originalPoints.forEach(function (point) {
  64665. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  64666. var newPoint = new IndexedVector2(point, _this.elements.length);
  64667. result.push(newPoint);
  64668. _this.elements.push(newPoint);
  64669. }
  64670. });
  64671. return result;
  64672. };
  64673. PolygonPoints.prototype.computeBounds = function () {
  64674. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  64675. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  64676. this.elements.forEach(function (point) {
  64677. // x
  64678. if (point.x < lmin.x) {
  64679. lmin.x = point.x;
  64680. }
  64681. else if (point.x > lmax.x) {
  64682. lmax.x = point.x;
  64683. }
  64684. // y
  64685. if (point.y < lmin.y) {
  64686. lmin.y = point.y;
  64687. }
  64688. else if (point.y > lmax.y) {
  64689. lmax.y = point.y;
  64690. }
  64691. });
  64692. return {
  64693. min: lmin,
  64694. max: lmax,
  64695. width: lmax.x - lmin.x,
  64696. height: lmax.y - lmin.y
  64697. };
  64698. };
  64699. return PolygonPoints;
  64700. }());
  64701. var Polygon = /** @class */ (function () {
  64702. function Polygon() {
  64703. }
  64704. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  64705. return [
  64706. new BABYLON.Vector2(xmin, ymin),
  64707. new BABYLON.Vector2(xmax, ymin),
  64708. new BABYLON.Vector2(xmax, ymax),
  64709. new BABYLON.Vector2(xmin, ymax)
  64710. ];
  64711. };
  64712. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  64713. if (cx === void 0) { cx = 0; }
  64714. if (cy === void 0) { cy = 0; }
  64715. if (numberOfSides === void 0) { numberOfSides = 32; }
  64716. var result = new Array();
  64717. var angle = 0;
  64718. var increment = (Math.PI * 2) / numberOfSides;
  64719. for (var i = 0; i < numberOfSides; i++) {
  64720. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  64721. angle -= increment;
  64722. }
  64723. return result;
  64724. };
  64725. Polygon.Parse = function (input) {
  64726. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  64727. var i, result = [];
  64728. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  64729. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  64730. }
  64731. return result;
  64732. };
  64733. Polygon.StartingAt = function (x, y) {
  64734. return BABYLON.Path2.StartingAt(x, y);
  64735. };
  64736. return Polygon;
  64737. }());
  64738. BABYLON.Polygon = Polygon;
  64739. var PolygonMeshBuilder = /** @class */ (function () {
  64740. function PolygonMeshBuilder(name, contours, scene) {
  64741. this._points = new PolygonPoints();
  64742. this._outlinepoints = new PolygonPoints();
  64743. this._holes = new Array();
  64744. this._epoints = new Array();
  64745. this._eholes = new Array();
  64746. this._name = name;
  64747. this._scene = scene;
  64748. var points;
  64749. if (contours instanceof BABYLON.Path2) {
  64750. points = contours.getPoints();
  64751. }
  64752. else {
  64753. points = contours;
  64754. }
  64755. this._addToepoint(points);
  64756. this._points.add(points);
  64757. this._outlinepoints.add(points);
  64758. }
  64759. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  64760. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  64761. var p = points_1[_i];
  64762. this._epoints.push(p.x, p.y);
  64763. }
  64764. };
  64765. PolygonMeshBuilder.prototype.addHole = function (hole) {
  64766. this._points.add(hole);
  64767. var holepoints = new PolygonPoints();
  64768. holepoints.add(hole);
  64769. this._holes.push(holepoints);
  64770. this._eholes.push(this._epoints.length / 2);
  64771. this._addToepoint(hole);
  64772. return this;
  64773. };
  64774. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  64775. var _this = this;
  64776. if (updatable === void 0) { updatable = false; }
  64777. if (depth === void 0) { depth = 0; }
  64778. var result = new BABYLON.Mesh(this._name, this._scene);
  64779. var normals = new Array();
  64780. var positions = new Array();
  64781. var uvs = new Array();
  64782. var bounds = this._points.computeBounds();
  64783. this._points.elements.forEach(function (p) {
  64784. normals.push(0, 1.0, 0);
  64785. positions.push(p.x, 0, p.y);
  64786. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  64787. });
  64788. var indices = new Array();
  64789. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  64790. for (var i = 0; i < res.length; i++) {
  64791. indices.push(res[i]);
  64792. }
  64793. if (depth > 0) {
  64794. var positionscount = (positions.length / 3); //get the current pointcount
  64795. this._points.elements.forEach(function (p) {
  64796. normals.push(0, -1.0, 0);
  64797. positions.push(p.x, -depth, p.y);
  64798. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  64799. });
  64800. var totalCount = indices.length;
  64801. for (var i = 0; i < totalCount; i += 3) {
  64802. var i0 = indices[i + 0];
  64803. var i1 = indices[i + 1];
  64804. var i2 = indices[i + 2];
  64805. indices.push(i2 + positionscount);
  64806. indices.push(i1 + positionscount);
  64807. indices.push(i0 + positionscount);
  64808. }
  64809. //Add the sides
  64810. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  64811. this._holes.forEach(function (hole) {
  64812. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  64813. });
  64814. }
  64815. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  64816. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  64817. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  64818. result.setIndices(indices);
  64819. return result;
  64820. };
  64821. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  64822. var StartIndex = positions.length / 3;
  64823. var ulength = 0;
  64824. for (var i = 0; i < points.elements.length; i++) {
  64825. var p = points.elements[i];
  64826. var p1;
  64827. if ((i + 1) > points.elements.length - 1) {
  64828. p1 = points.elements[0];
  64829. }
  64830. else {
  64831. p1 = points.elements[i + 1];
  64832. }
  64833. positions.push(p.x, 0, p.y);
  64834. positions.push(p.x, -depth, p.y);
  64835. positions.push(p1.x, 0, p1.y);
  64836. positions.push(p1.x, -depth, p1.y);
  64837. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  64838. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  64839. var v3 = v2.subtract(v1);
  64840. var v4 = new BABYLON.Vector3(0, 1, 0);
  64841. var vn = BABYLON.Vector3.Cross(v3, v4);
  64842. vn = vn.normalize();
  64843. uvs.push(ulength / bounds.width, 0);
  64844. uvs.push(ulength / bounds.width, 1);
  64845. ulength += v3.length();
  64846. uvs.push((ulength / bounds.width), 0);
  64847. uvs.push((ulength / bounds.width), 1);
  64848. if (!flip) {
  64849. normals.push(-vn.x, -vn.y, -vn.z);
  64850. normals.push(-vn.x, -vn.y, -vn.z);
  64851. normals.push(-vn.x, -vn.y, -vn.z);
  64852. normals.push(-vn.x, -vn.y, -vn.z);
  64853. indices.push(StartIndex);
  64854. indices.push(StartIndex + 1);
  64855. indices.push(StartIndex + 2);
  64856. indices.push(StartIndex + 1);
  64857. indices.push(StartIndex + 3);
  64858. indices.push(StartIndex + 2);
  64859. }
  64860. else {
  64861. normals.push(vn.x, vn.y, vn.z);
  64862. normals.push(vn.x, vn.y, vn.z);
  64863. normals.push(vn.x, vn.y, vn.z);
  64864. normals.push(vn.x, vn.y, vn.z);
  64865. indices.push(StartIndex);
  64866. indices.push(StartIndex + 2);
  64867. indices.push(StartIndex + 1);
  64868. indices.push(StartIndex + 1);
  64869. indices.push(StartIndex + 2);
  64870. indices.push(StartIndex + 3);
  64871. }
  64872. StartIndex += 4;
  64873. }
  64874. ;
  64875. };
  64876. return PolygonMeshBuilder;
  64877. }());
  64878. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  64879. })(BABYLON || (BABYLON = {}));
  64880. //# sourceMappingURL=babylon.polygonMesh.js.map
  64881. var BABYLON;
  64882. (function (BABYLON) {
  64883. // Unique ID when we import meshes from Babylon to CSG
  64884. var currentCSGMeshId = 0;
  64885. // # class Vertex
  64886. // Represents a vertex of a polygon. Use your own vertex class instead of this
  64887. // one to provide additional features like texture coordinates and vertex
  64888. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  64889. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  64890. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  64891. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  64892. // is not used anywhere else.
  64893. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  64894. var Vertex = /** @class */ (function () {
  64895. function Vertex(pos, normal, uv) {
  64896. this.pos = pos;
  64897. this.normal = normal;
  64898. this.uv = uv;
  64899. }
  64900. Vertex.prototype.clone = function () {
  64901. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  64902. };
  64903. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  64904. // orientation of a polygon is flipped.
  64905. Vertex.prototype.flip = function () {
  64906. this.normal = this.normal.scale(-1);
  64907. };
  64908. // Create a new vertex between this vertex and `other` by linearly
  64909. // interpolating all properties using a parameter of `t`. Subclasses should
  64910. // override this to interpolate additional properties.
  64911. Vertex.prototype.interpolate = function (other, t) {
  64912. 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));
  64913. };
  64914. return Vertex;
  64915. }());
  64916. // # class Plane
  64917. // Represents a plane in 3D space.
  64918. var Plane = /** @class */ (function () {
  64919. function Plane(normal, w) {
  64920. this.normal = normal;
  64921. this.w = w;
  64922. }
  64923. Plane.FromPoints = function (a, b, c) {
  64924. var v0 = c.subtract(a);
  64925. var v1 = b.subtract(a);
  64926. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  64927. return null;
  64928. }
  64929. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  64930. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  64931. };
  64932. Plane.prototype.clone = function () {
  64933. return new Plane(this.normal.clone(), this.w);
  64934. };
  64935. Plane.prototype.flip = function () {
  64936. this.normal.scaleInPlace(-1);
  64937. this.w = -this.w;
  64938. };
  64939. // Split `polygon` by this plane if needed, then put the polygon or polygon
  64940. // fragments in the appropriate lists. Coplanar polygons go into either
  64941. // `coplanarFront` or `coplanarBack` depending on their orientation with
  64942. // respect to this plane. Polygons in front or in back of this plane go into
  64943. // either `front` or `back`.
  64944. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  64945. var COPLANAR = 0;
  64946. var FRONT = 1;
  64947. var BACK = 2;
  64948. var SPANNING = 3;
  64949. // Classify each point as well as the entire polygon into one of the above
  64950. // four classes.
  64951. var polygonType = 0;
  64952. var types = [];
  64953. var i;
  64954. var t;
  64955. for (i = 0; i < polygon.vertices.length; i++) {
  64956. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  64957. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  64958. polygonType |= type;
  64959. types.push(type);
  64960. }
  64961. // Put the polygon in the correct list, splitting it when necessary.
  64962. switch (polygonType) {
  64963. case COPLANAR:
  64964. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  64965. break;
  64966. case FRONT:
  64967. front.push(polygon);
  64968. break;
  64969. case BACK:
  64970. back.push(polygon);
  64971. break;
  64972. case SPANNING:
  64973. var f = [], b = [];
  64974. for (i = 0; i < polygon.vertices.length; i++) {
  64975. var j = (i + 1) % polygon.vertices.length;
  64976. var ti = types[i], tj = types[j];
  64977. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  64978. if (ti !== BACK)
  64979. f.push(vi);
  64980. if (ti !== FRONT)
  64981. b.push(ti !== BACK ? vi.clone() : vi);
  64982. if ((ti | tj) === SPANNING) {
  64983. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  64984. var v = vi.interpolate(vj, t);
  64985. f.push(v);
  64986. b.push(v.clone());
  64987. }
  64988. }
  64989. var poly;
  64990. if (f.length >= 3) {
  64991. poly = new Polygon(f, polygon.shared);
  64992. if (poly.plane)
  64993. front.push(poly);
  64994. }
  64995. if (b.length >= 3) {
  64996. poly = new Polygon(b, polygon.shared);
  64997. if (poly.plane)
  64998. back.push(poly);
  64999. }
  65000. break;
  65001. }
  65002. };
  65003. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  65004. // point is on the plane.
  65005. Plane.EPSILON = 1e-5;
  65006. return Plane;
  65007. }());
  65008. // # class Polygon
  65009. // Represents a convex polygon. The vertices used to initialize a polygon must
  65010. // be coplanar and form a convex loop.
  65011. //
  65012. // Each convex polygon has a `shared` property, which is shared between all
  65013. // polygons that are clones of each other or were split from the same polygon.
  65014. // This can be used to define per-polygon properties (such as surface color).
  65015. var Polygon = /** @class */ (function () {
  65016. function Polygon(vertices, shared) {
  65017. this.vertices = vertices;
  65018. this.shared = shared;
  65019. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  65020. }
  65021. Polygon.prototype.clone = function () {
  65022. var vertices = this.vertices.map(function (v) { return v.clone(); });
  65023. return new Polygon(vertices, this.shared);
  65024. };
  65025. Polygon.prototype.flip = function () {
  65026. this.vertices.reverse().map(function (v) { v.flip(); });
  65027. this.plane.flip();
  65028. };
  65029. return Polygon;
  65030. }());
  65031. // # class Node
  65032. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  65033. // by picking a polygon to split along. That polygon (and all other coplanar
  65034. // polygons) are added directly to that node and the other polygons are added to
  65035. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  65036. // no distinction between internal and leaf nodes.
  65037. var Node = /** @class */ (function () {
  65038. function Node(polygons) {
  65039. this.plane = null;
  65040. this.front = null;
  65041. this.back = null;
  65042. this.polygons = new Array();
  65043. if (polygons) {
  65044. this.build(polygons);
  65045. }
  65046. }
  65047. Node.prototype.clone = function () {
  65048. var node = new Node();
  65049. node.plane = this.plane && this.plane.clone();
  65050. node.front = this.front && this.front.clone();
  65051. node.back = this.back && this.back.clone();
  65052. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  65053. return node;
  65054. };
  65055. // Convert solid space to empty space and empty space to solid space.
  65056. Node.prototype.invert = function () {
  65057. for (var i = 0; i < this.polygons.length; i++) {
  65058. this.polygons[i].flip();
  65059. }
  65060. if (this.plane) {
  65061. this.plane.flip();
  65062. }
  65063. if (this.front) {
  65064. this.front.invert();
  65065. }
  65066. if (this.back) {
  65067. this.back.invert();
  65068. }
  65069. var temp = this.front;
  65070. this.front = this.back;
  65071. this.back = temp;
  65072. };
  65073. // Recursively remove all polygons in `polygons` that are inside this BSP
  65074. // tree.
  65075. Node.prototype.clipPolygons = function (polygons) {
  65076. if (!this.plane)
  65077. return polygons.slice();
  65078. var front = new Array(), back = new Array();
  65079. for (var i = 0; i < polygons.length; i++) {
  65080. this.plane.splitPolygon(polygons[i], front, back, front, back);
  65081. }
  65082. if (this.front) {
  65083. front = this.front.clipPolygons(front);
  65084. }
  65085. if (this.back) {
  65086. back = this.back.clipPolygons(back);
  65087. }
  65088. else {
  65089. back = [];
  65090. }
  65091. return front.concat(back);
  65092. };
  65093. // Remove all polygons in this BSP tree that are inside the other BSP tree
  65094. // `bsp`.
  65095. Node.prototype.clipTo = function (bsp) {
  65096. this.polygons = bsp.clipPolygons(this.polygons);
  65097. if (this.front)
  65098. this.front.clipTo(bsp);
  65099. if (this.back)
  65100. this.back.clipTo(bsp);
  65101. };
  65102. // Return a list of all polygons in this BSP tree.
  65103. Node.prototype.allPolygons = function () {
  65104. var polygons = this.polygons.slice();
  65105. if (this.front)
  65106. polygons = polygons.concat(this.front.allPolygons());
  65107. if (this.back)
  65108. polygons = polygons.concat(this.back.allPolygons());
  65109. return polygons;
  65110. };
  65111. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  65112. // new polygons are filtered down to the bottom of the tree and become new
  65113. // nodes there. Each set of polygons is partitioned using the first polygon
  65114. // (no heuristic is used to pick a good split).
  65115. Node.prototype.build = function (polygons) {
  65116. if (!polygons.length)
  65117. return;
  65118. if (!this.plane)
  65119. this.plane = polygons[0].plane.clone();
  65120. var front = new Array(), back = new Array();
  65121. for (var i = 0; i < polygons.length; i++) {
  65122. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  65123. }
  65124. if (front.length) {
  65125. if (!this.front)
  65126. this.front = new Node();
  65127. this.front.build(front);
  65128. }
  65129. if (back.length) {
  65130. if (!this.back)
  65131. this.back = new Node();
  65132. this.back.build(back);
  65133. }
  65134. };
  65135. return Node;
  65136. }());
  65137. var CSG = /** @class */ (function () {
  65138. function CSG() {
  65139. this.polygons = new Array();
  65140. }
  65141. // Convert BABYLON.Mesh to BABYLON.CSG
  65142. CSG.FromMesh = function (mesh) {
  65143. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  65144. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  65145. if (mesh instanceof BABYLON.Mesh) {
  65146. mesh.computeWorldMatrix(true);
  65147. matrix = mesh.getWorldMatrix();
  65148. meshPosition = mesh.position.clone();
  65149. meshRotation = mesh.rotation.clone();
  65150. if (mesh.rotationQuaternion) {
  65151. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  65152. }
  65153. meshScaling = mesh.scaling.clone();
  65154. }
  65155. else {
  65156. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  65157. }
  65158. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  65159. var subMeshes = mesh.subMeshes;
  65160. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  65161. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  65162. vertices = [];
  65163. for (var j = 0; j < 3; j++) {
  65164. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  65165. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  65166. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  65167. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  65168. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  65169. vertex = new Vertex(position, normal, uv);
  65170. vertices.push(vertex);
  65171. }
  65172. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  65173. // To handle the case of degenerated triangle
  65174. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  65175. if (polygon.plane)
  65176. polygons.push(polygon);
  65177. }
  65178. }
  65179. var csg = CSG.FromPolygons(polygons);
  65180. csg.matrix = matrix;
  65181. csg.position = meshPosition;
  65182. csg.rotation = meshRotation;
  65183. csg.scaling = meshScaling;
  65184. csg.rotationQuaternion = meshRotationQuaternion;
  65185. currentCSGMeshId++;
  65186. return csg;
  65187. };
  65188. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  65189. CSG.FromPolygons = function (polygons) {
  65190. var csg = new CSG();
  65191. csg.polygons = polygons;
  65192. return csg;
  65193. };
  65194. CSG.prototype.clone = function () {
  65195. var csg = new CSG();
  65196. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  65197. csg.copyTransformAttributes(this);
  65198. return csg;
  65199. };
  65200. CSG.prototype.union = function (csg) {
  65201. var a = new Node(this.clone().polygons);
  65202. var b = new Node(csg.clone().polygons);
  65203. a.clipTo(b);
  65204. b.clipTo(a);
  65205. b.invert();
  65206. b.clipTo(a);
  65207. b.invert();
  65208. a.build(b.allPolygons());
  65209. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  65210. };
  65211. CSG.prototype.unionInPlace = function (csg) {
  65212. var a = new Node(this.polygons);
  65213. var b = new Node(csg.polygons);
  65214. a.clipTo(b);
  65215. b.clipTo(a);
  65216. b.invert();
  65217. b.clipTo(a);
  65218. b.invert();
  65219. a.build(b.allPolygons());
  65220. this.polygons = a.allPolygons();
  65221. };
  65222. CSG.prototype.subtract = function (csg) {
  65223. var a = new Node(this.clone().polygons);
  65224. var b = new Node(csg.clone().polygons);
  65225. a.invert();
  65226. a.clipTo(b);
  65227. b.clipTo(a);
  65228. b.invert();
  65229. b.clipTo(a);
  65230. b.invert();
  65231. a.build(b.allPolygons());
  65232. a.invert();
  65233. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  65234. };
  65235. CSG.prototype.subtractInPlace = function (csg) {
  65236. var a = new Node(this.polygons);
  65237. var b = new Node(csg.polygons);
  65238. a.invert();
  65239. a.clipTo(b);
  65240. b.clipTo(a);
  65241. b.invert();
  65242. b.clipTo(a);
  65243. b.invert();
  65244. a.build(b.allPolygons());
  65245. a.invert();
  65246. this.polygons = a.allPolygons();
  65247. };
  65248. CSG.prototype.intersect = function (csg) {
  65249. var a = new Node(this.clone().polygons);
  65250. var b = new Node(csg.clone().polygons);
  65251. a.invert();
  65252. b.clipTo(a);
  65253. b.invert();
  65254. a.clipTo(b);
  65255. b.clipTo(a);
  65256. a.build(b.allPolygons());
  65257. a.invert();
  65258. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  65259. };
  65260. CSG.prototype.intersectInPlace = function (csg) {
  65261. var a = new Node(this.polygons);
  65262. var b = new Node(csg.polygons);
  65263. a.invert();
  65264. b.clipTo(a);
  65265. b.invert();
  65266. a.clipTo(b);
  65267. b.clipTo(a);
  65268. a.build(b.allPolygons());
  65269. a.invert();
  65270. this.polygons = a.allPolygons();
  65271. };
  65272. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  65273. // not modified.
  65274. CSG.prototype.inverse = function () {
  65275. var csg = this.clone();
  65276. csg.inverseInPlace();
  65277. return csg;
  65278. };
  65279. CSG.prototype.inverseInPlace = function () {
  65280. this.polygons.map(function (p) { p.flip(); });
  65281. };
  65282. // This is used to keep meshes transformations so they can be restored
  65283. // when we build back a Babylon Mesh
  65284. // NB : All CSG operations are performed in world coordinates
  65285. CSG.prototype.copyTransformAttributes = function (csg) {
  65286. this.matrix = csg.matrix;
  65287. this.position = csg.position;
  65288. this.rotation = csg.rotation;
  65289. this.scaling = csg.scaling;
  65290. this.rotationQuaternion = csg.rotationQuaternion;
  65291. return this;
  65292. };
  65293. // Build Raw mesh from CSG
  65294. // Coordinates here are in world space
  65295. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  65296. var matrix = this.matrix.clone();
  65297. matrix.invert();
  65298. 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;
  65299. if (keepSubMeshes) {
  65300. // Sort Polygons, since subMeshes are indices range
  65301. polygons.sort(function (a, b) {
  65302. if (a.shared.meshId === b.shared.meshId) {
  65303. return a.shared.subMeshId - b.shared.subMeshId;
  65304. }
  65305. else {
  65306. return a.shared.meshId - b.shared.meshId;
  65307. }
  65308. });
  65309. }
  65310. for (var i = 0, il = polygons.length; i < il; i++) {
  65311. polygon = polygons[i];
  65312. // Building SubMeshes
  65313. if (!subMesh_dict[polygon.shared.meshId]) {
  65314. subMesh_dict[polygon.shared.meshId] = {};
  65315. }
  65316. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  65317. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  65318. indexStart: +Infinity,
  65319. indexEnd: -Infinity,
  65320. materialIndex: polygon.shared.materialIndex
  65321. };
  65322. }
  65323. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  65324. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  65325. polygonIndices[0] = 0;
  65326. polygonIndices[1] = j - 1;
  65327. polygonIndices[2] = j;
  65328. for (var k = 0; k < 3; k++) {
  65329. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  65330. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  65331. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  65332. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  65333. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  65334. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  65335. // Check if 2 points can be merged
  65336. if (!(typeof vertex_idx !== 'undefined' &&
  65337. normals[vertex_idx * 3] === localNormal.x &&
  65338. normals[vertex_idx * 3 + 1] === localNormal.y &&
  65339. normals[vertex_idx * 3 + 2] === localNormal.z &&
  65340. uvs[vertex_idx * 2] === uv.x &&
  65341. uvs[vertex_idx * 2 + 1] === uv.y)) {
  65342. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  65343. uvs.push(uv.x, uv.y);
  65344. normals.push(normal.x, normal.y, normal.z);
  65345. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  65346. }
  65347. indices.push(vertex_idx);
  65348. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  65349. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  65350. currentIndex++;
  65351. }
  65352. }
  65353. }
  65354. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  65355. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  65356. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  65357. mesh.setIndices(indices, null);
  65358. if (keepSubMeshes) {
  65359. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  65360. var materialIndexOffset = 0, materialMaxIndex;
  65361. mesh.subMeshes = new Array();
  65362. for (var m in subMesh_dict) {
  65363. materialMaxIndex = -1;
  65364. for (var sm in subMesh_dict[m]) {
  65365. subMesh_obj = subMesh_dict[m][sm];
  65366. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  65367. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  65368. }
  65369. materialIndexOffset += ++materialMaxIndex;
  65370. }
  65371. }
  65372. return mesh;
  65373. };
  65374. // Build Mesh from CSG taking material and transforms into account
  65375. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  65376. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  65377. mesh.material = material;
  65378. mesh.position.copyFrom(this.position);
  65379. mesh.rotation.copyFrom(this.rotation);
  65380. if (this.rotationQuaternion) {
  65381. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  65382. }
  65383. mesh.scaling.copyFrom(this.scaling);
  65384. mesh.computeWorldMatrix(true);
  65385. return mesh;
  65386. };
  65387. return CSG;
  65388. }());
  65389. BABYLON.CSG = CSG;
  65390. })(BABYLON || (BABYLON = {}));
  65391. //# sourceMappingURL=babylon.csg.js.map
  65392. var BABYLON;
  65393. (function (BABYLON) {
  65394. var LensFlare = /** @class */ (function () {
  65395. function LensFlare(size, position, color, imgUrl, system) {
  65396. this.size = size;
  65397. this.position = position;
  65398. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  65399. this.color = color || new BABYLON.Color3(1, 1, 1);
  65400. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  65401. this._system = system;
  65402. system.lensFlares.push(this);
  65403. }
  65404. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  65405. return new LensFlare(size, position, color, imgUrl, system);
  65406. };
  65407. LensFlare.prototype.dispose = function () {
  65408. if (this.texture) {
  65409. this.texture.dispose();
  65410. }
  65411. // Remove from scene
  65412. var index = this._system.lensFlares.indexOf(this);
  65413. this._system.lensFlares.splice(index, 1);
  65414. };
  65415. ;
  65416. return LensFlare;
  65417. }());
  65418. BABYLON.LensFlare = LensFlare;
  65419. })(BABYLON || (BABYLON = {}));
  65420. //# sourceMappingURL=babylon.lensFlare.js.map
  65421. var BABYLON;
  65422. (function (BABYLON) {
  65423. var LensFlareSystem = /** @class */ (function () {
  65424. function LensFlareSystem(name, emitter, scene) {
  65425. this.name = name;
  65426. this.lensFlares = new Array();
  65427. this.borderLimit = 300;
  65428. this.viewportBorder = 0;
  65429. this.layerMask = 0x0FFFFFFF;
  65430. this._vertexBuffers = {};
  65431. this._isEnabled = true;
  65432. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  65433. this._emitter = emitter;
  65434. this.id = name;
  65435. scene.lensFlareSystems.push(this);
  65436. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  65437. var engine = scene.getEngine();
  65438. // VBO
  65439. var vertices = [];
  65440. vertices.push(1, 1);
  65441. vertices.push(-1, 1);
  65442. vertices.push(-1, -1);
  65443. vertices.push(1, -1);
  65444. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65445. // Indices
  65446. var indices = [];
  65447. indices.push(0);
  65448. indices.push(1);
  65449. indices.push(2);
  65450. indices.push(0);
  65451. indices.push(2);
  65452. indices.push(3);
  65453. this._indexBuffer = engine.createIndexBuffer(indices);
  65454. // Effects
  65455. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  65456. }
  65457. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  65458. get: function () {
  65459. return this._isEnabled;
  65460. },
  65461. set: function (value) {
  65462. this._isEnabled = value;
  65463. },
  65464. enumerable: true,
  65465. configurable: true
  65466. });
  65467. LensFlareSystem.prototype.getScene = function () {
  65468. return this._scene;
  65469. };
  65470. LensFlareSystem.prototype.getEmitter = function () {
  65471. return this._emitter;
  65472. };
  65473. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  65474. this._emitter = newEmitter;
  65475. };
  65476. LensFlareSystem.prototype.getEmitterPosition = function () {
  65477. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  65478. };
  65479. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  65480. var position = this.getEmitterPosition();
  65481. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  65482. this._positionX = position.x;
  65483. this._positionY = position.y;
  65484. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  65485. if (this.viewportBorder > 0) {
  65486. globalViewport.x -= this.viewportBorder;
  65487. globalViewport.y -= this.viewportBorder;
  65488. globalViewport.width += this.viewportBorder * 2;
  65489. globalViewport.height += this.viewportBorder * 2;
  65490. position.x += this.viewportBorder;
  65491. position.y += this.viewportBorder;
  65492. this._positionX += this.viewportBorder;
  65493. this._positionY += this.viewportBorder;
  65494. }
  65495. if (position.z > 0) {
  65496. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  65497. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  65498. return true;
  65499. }
  65500. return true;
  65501. }
  65502. return false;
  65503. };
  65504. LensFlareSystem.prototype._isVisible = function () {
  65505. if (!this._isEnabled || !this._scene.activeCamera) {
  65506. return false;
  65507. }
  65508. var emitterPosition = this.getEmitterPosition();
  65509. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  65510. var distance = direction.length();
  65511. direction.normalize();
  65512. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  65513. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  65514. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  65515. };
  65516. LensFlareSystem.prototype.render = function () {
  65517. if (!this._effect.isReady() || !this._scene.activeCamera)
  65518. return false;
  65519. var engine = this._scene.getEngine();
  65520. var viewport = this._scene.activeCamera.viewport;
  65521. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  65522. // Position
  65523. if (!this.computeEffectivePosition(globalViewport)) {
  65524. return false;
  65525. }
  65526. // Visibility
  65527. if (!this._isVisible()) {
  65528. return false;
  65529. }
  65530. // Intensity
  65531. var awayX;
  65532. var awayY;
  65533. if (this._positionX < this.borderLimit + globalViewport.x) {
  65534. awayX = this.borderLimit + globalViewport.x - this._positionX;
  65535. }
  65536. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  65537. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  65538. }
  65539. else {
  65540. awayX = 0;
  65541. }
  65542. if (this._positionY < this.borderLimit + globalViewport.y) {
  65543. awayY = this.borderLimit + globalViewport.y - this._positionY;
  65544. }
  65545. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  65546. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  65547. }
  65548. else {
  65549. awayY = 0;
  65550. }
  65551. var away = (awayX > awayY) ? awayX : awayY;
  65552. away -= this.viewportBorder;
  65553. if (away > this.borderLimit) {
  65554. away = this.borderLimit;
  65555. }
  65556. var intensity = 1.0 - (away / this.borderLimit);
  65557. if (intensity < 0) {
  65558. return false;
  65559. }
  65560. if (intensity > 1.0) {
  65561. intensity = 1.0;
  65562. }
  65563. if (this.viewportBorder > 0) {
  65564. globalViewport.x += this.viewportBorder;
  65565. globalViewport.y += this.viewportBorder;
  65566. globalViewport.width -= this.viewportBorder * 2;
  65567. globalViewport.height -= this.viewportBorder * 2;
  65568. this._positionX -= this.viewportBorder;
  65569. this._positionY -= this.viewportBorder;
  65570. }
  65571. // Position
  65572. var centerX = globalViewport.x + globalViewport.width / 2;
  65573. var centerY = globalViewport.y + globalViewport.height / 2;
  65574. var distX = centerX - this._positionX;
  65575. var distY = centerY - this._positionY;
  65576. // Effects
  65577. engine.enableEffect(this._effect);
  65578. engine.setState(false);
  65579. engine.setDepthBuffer(false);
  65580. // VBOs
  65581. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65582. // Flares
  65583. for (var index = 0; index < this.lensFlares.length; index++) {
  65584. var flare = this.lensFlares[index];
  65585. engine.setAlphaMode(flare.alphaMode);
  65586. var x = centerX - (distX * flare.position);
  65587. var y = centerY - (distY * flare.position);
  65588. var cw = flare.size;
  65589. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  65590. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  65591. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  65592. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  65593. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  65594. // Texture
  65595. this._effect.setTexture("textureSampler", flare.texture);
  65596. // Color
  65597. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  65598. // Draw order
  65599. engine.draw(true, 0, 6);
  65600. }
  65601. engine.setDepthBuffer(true);
  65602. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65603. return true;
  65604. };
  65605. LensFlareSystem.prototype.dispose = function () {
  65606. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65607. if (vertexBuffer) {
  65608. vertexBuffer.dispose();
  65609. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65610. }
  65611. if (this._indexBuffer) {
  65612. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  65613. this._indexBuffer = null;
  65614. }
  65615. while (this.lensFlares.length) {
  65616. this.lensFlares[0].dispose();
  65617. }
  65618. // Remove from scene
  65619. var index = this._scene.lensFlareSystems.indexOf(this);
  65620. this._scene.lensFlareSystems.splice(index, 1);
  65621. };
  65622. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  65623. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  65624. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  65625. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  65626. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  65627. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  65628. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  65629. var parsedFlare = parsedLensFlareSystem.flares[index];
  65630. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  65631. }
  65632. return lensFlareSystem;
  65633. };
  65634. LensFlareSystem.prototype.serialize = function () {
  65635. var serializationObject = {};
  65636. serializationObject.id = this.id;
  65637. serializationObject.name = this.name;
  65638. serializationObject.emitterId = this.getEmitter().id;
  65639. serializationObject.borderLimit = this.borderLimit;
  65640. serializationObject.flares = [];
  65641. for (var index = 0; index < this.lensFlares.length; index++) {
  65642. var flare = this.lensFlares[index];
  65643. serializationObject.flares.push({
  65644. size: flare.size,
  65645. position: flare.position,
  65646. color: flare.color.asArray(),
  65647. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  65648. });
  65649. }
  65650. return serializationObject;
  65651. };
  65652. return LensFlareSystem;
  65653. }());
  65654. BABYLON.LensFlareSystem = LensFlareSystem;
  65655. })(BABYLON || (BABYLON = {}));
  65656. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  65657. var BABYLON;
  65658. (function (BABYLON) {
  65659. /**
  65660. * This is a holder class for the physics joint created by the physics plugin.
  65661. * It holds a set of functions to control the underlying joint.
  65662. */
  65663. var PhysicsJoint = /** @class */ (function () {
  65664. function PhysicsJoint(type, jointData) {
  65665. this.type = type;
  65666. this.jointData = jointData;
  65667. jointData.nativeParams = jointData.nativeParams || {};
  65668. }
  65669. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  65670. get: function () {
  65671. return this._physicsJoint;
  65672. },
  65673. set: function (newJoint) {
  65674. if (this._physicsJoint) {
  65675. //remove from the wolrd
  65676. }
  65677. this._physicsJoint = newJoint;
  65678. },
  65679. enumerable: true,
  65680. configurable: true
  65681. });
  65682. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  65683. set: function (physicsPlugin) {
  65684. this._physicsPlugin = physicsPlugin;
  65685. },
  65686. enumerable: true,
  65687. configurable: true
  65688. });
  65689. /**
  65690. * Execute a function that is physics-plugin specific.
  65691. * @param {Function} func the function that will be executed.
  65692. * It accepts two parameters: the physics world and the physics joint.
  65693. */
  65694. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  65695. func(this._physicsPlugin.world, this._physicsJoint);
  65696. };
  65697. //TODO check if the native joints are the same
  65698. //Joint Types
  65699. PhysicsJoint.DistanceJoint = 0;
  65700. PhysicsJoint.HingeJoint = 1;
  65701. PhysicsJoint.BallAndSocketJoint = 2;
  65702. PhysicsJoint.WheelJoint = 3;
  65703. PhysicsJoint.SliderJoint = 4;
  65704. //OIMO
  65705. PhysicsJoint.PrismaticJoint = 5;
  65706. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  65707. PhysicsJoint.UniversalJoint = 6;
  65708. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  65709. //Cannon
  65710. //Similar to a Ball-Joint. Different in params
  65711. PhysicsJoint.PointToPointJoint = 8;
  65712. //Cannon only at the moment
  65713. PhysicsJoint.SpringJoint = 9;
  65714. PhysicsJoint.LockJoint = 10;
  65715. return PhysicsJoint;
  65716. }());
  65717. BABYLON.PhysicsJoint = PhysicsJoint;
  65718. /**
  65719. * A class representing a physics distance joint.
  65720. */
  65721. var DistanceJoint = /** @class */ (function (_super) {
  65722. __extends(DistanceJoint, _super);
  65723. function DistanceJoint(jointData) {
  65724. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  65725. }
  65726. /**
  65727. * Update the predefined distance.
  65728. */
  65729. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  65730. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  65731. };
  65732. return DistanceJoint;
  65733. }(PhysicsJoint));
  65734. BABYLON.DistanceJoint = DistanceJoint;
  65735. var MotorEnabledJoint = /** @class */ (function (_super) {
  65736. __extends(MotorEnabledJoint, _super);
  65737. function MotorEnabledJoint(type, jointData) {
  65738. return _super.call(this, type, jointData) || this;
  65739. }
  65740. /**
  65741. * Set the motor values.
  65742. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65743. * @param {number} force the force to apply
  65744. * @param {number} maxForce max force for this motor.
  65745. */
  65746. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  65747. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  65748. };
  65749. /**
  65750. * Set the motor's limits.
  65751. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65752. */
  65753. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  65754. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  65755. };
  65756. return MotorEnabledJoint;
  65757. }(PhysicsJoint));
  65758. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  65759. /**
  65760. * This class represents a single hinge physics joint
  65761. */
  65762. var HingeJoint = /** @class */ (function (_super) {
  65763. __extends(HingeJoint, _super);
  65764. function HingeJoint(jointData) {
  65765. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  65766. }
  65767. /**
  65768. * Set the motor values.
  65769. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65770. * @param {number} force the force to apply
  65771. * @param {number} maxForce max force for this motor.
  65772. */
  65773. HingeJoint.prototype.setMotor = function (force, maxForce) {
  65774. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  65775. };
  65776. /**
  65777. * Set the motor's limits.
  65778. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65779. */
  65780. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  65781. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  65782. };
  65783. return HingeJoint;
  65784. }(MotorEnabledJoint));
  65785. BABYLON.HingeJoint = HingeJoint;
  65786. /**
  65787. * This class represents a dual hinge physics joint (same as wheel joint)
  65788. */
  65789. var Hinge2Joint = /** @class */ (function (_super) {
  65790. __extends(Hinge2Joint, _super);
  65791. function Hinge2Joint(jointData) {
  65792. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  65793. }
  65794. /**
  65795. * Set the motor values.
  65796. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65797. * @param {number} force the force to apply
  65798. * @param {number} maxForce max force for this motor.
  65799. * @param {motorIndex} the motor's index, 0 or 1.
  65800. */
  65801. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  65802. if (motorIndex === void 0) { motorIndex = 0; }
  65803. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  65804. };
  65805. /**
  65806. * Set the motor limits.
  65807. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65808. * @param {number} upperLimit the upper limit
  65809. * @param {number} lowerLimit lower limit
  65810. * @param {motorIndex} the motor's index, 0 or 1.
  65811. */
  65812. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  65813. if (motorIndex === void 0) { motorIndex = 0; }
  65814. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  65815. };
  65816. return Hinge2Joint;
  65817. }(MotorEnabledJoint));
  65818. BABYLON.Hinge2Joint = Hinge2Joint;
  65819. })(BABYLON || (BABYLON = {}));
  65820. //# sourceMappingURL=babylon.physicsJoint.js.map
  65821. var BABYLON;
  65822. (function (BABYLON) {
  65823. var PhysicsImpostor = /** @class */ (function () {
  65824. function PhysicsImpostor(object, type, _options, _scene) {
  65825. if (_options === void 0) { _options = { mass: 0 }; }
  65826. var _this = this;
  65827. this.object = object;
  65828. this.type = type;
  65829. this._options = _options;
  65830. this._scene = _scene;
  65831. this._bodyUpdateRequired = false;
  65832. this._onBeforePhysicsStepCallbacks = new Array();
  65833. this._onAfterPhysicsStepCallbacks = new Array();
  65834. this._onPhysicsCollideCallbacks = [];
  65835. this._deltaPosition = BABYLON.Vector3.Zero();
  65836. this._isDisposed = false;
  65837. //temp variables for parent rotation calculations
  65838. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  65839. this._tmpQuat = new BABYLON.Quaternion();
  65840. this._tmpQuat2 = new BABYLON.Quaternion();
  65841. /**
  65842. * this function is executed by the physics engine.
  65843. */
  65844. this.beforeStep = function () {
  65845. if (!_this._physicsEngine) {
  65846. return;
  65847. }
  65848. _this.object.translate(_this._deltaPosition, -1);
  65849. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  65850. _this.object.computeWorldMatrix(false);
  65851. if (_this.object.parent && _this.object.rotationQuaternion) {
  65852. _this.getParentsRotation();
  65853. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  65854. }
  65855. else {
  65856. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  65857. }
  65858. if (!_this._options.disableBidirectionalTransformation) {
  65859. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  65860. }
  65861. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  65862. func(_this);
  65863. });
  65864. };
  65865. /**
  65866. * this function is executed by the physics engine.
  65867. */
  65868. this.afterStep = function () {
  65869. if (!_this._physicsEngine) {
  65870. return;
  65871. }
  65872. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  65873. func(_this);
  65874. });
  65875. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  65876. // object has now its world rotation. needs to be converted to local.
  65877. if (_this.object.parent && _this.object.rotationQuaternion) {
  65878. _this.getParentsRotation();
  65879. _this._tmpQuat.conjugateInPlace();
  65880. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  65881. }
  65882. // take the position set and make it the absolute position of this object.
  65883. _this.object.setAbsolutePosition(_this.object.position);
  65884. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  65885. _this.object.translate(_this._deltaPosition, 1);
  65886. };
  65887. /**
  65888. * Legacy collision detection event support
  65889. */
  65890. this.onCollideEvent = null;
  65891. //event and body object due to cannon's event-based architecture.
  65892. this.onCollide = function (e) {
  65893. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  65894. return;
  65895. }
  65896. if (!_this._physicsEngine) {
  65897. return;
  65898. }
  65899. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  65900. if (otherImpostor) {
  65901. // Legacy collision detection event support
  65902. if (_this.onCollideEvent) {
  65903. _this.onCollideEvent(_this, otherImpostor);
  65904. }
  65905. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  65906. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  65907. }).forEach(function (obj) {
  65908. obj.callback(_this, otherImpostor);
  65909. });
  65910. }
  65911. };
  65912. //sanity check!
  65913. if (!this.object) {
  65914. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  65915. return;
  65916. }
  65917. //legacy support for old syntax.
  65918. if (!this._scene && object.getScene) {
  65919. this._scene = object.getScene();
  65920. }
  65921. if (!this._scene) {
  65922. return;
  65923. }
  65924. this._physicsEngine = this._scene.getPhysicsEngine();
  65925. if (!this._physicsEngine) {
  65926. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  65927. }
  65928. else {
  65929. //set the object's quaternion, if not set
  65930. if (!this.object.rotationQuaternion) {
  65931. if (this.object.rotation) {
  65932. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  65933. }
  65934. else {
  65935. this.object.rotationQuaternion = new BABYLON.Quaternion();
  65936. }
  65937. }
  65938. //default options params
  65939. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  65940. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  65941. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  65942. this._joints = [];
  65943. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  65944. if (!this.object.parent || this._options.ignoreParent) {
  65945. this._init();
  65946. }
  65947. else if (this.object.parent.physicsImpostor) {
  65948. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  65949. }
  65950. }
  65951. }
  65952. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  65953. get: function () {
  65954. return this._isDisposed;
  65955. },
  65956. enumerable: true,
  65957. configurable: true
  65958. });
  65959. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  65960. get: function () {
  65961. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  65962. },
  65963. set: function (value) {
  65964. this.setMass(value);
  65965. },
  65966. enumerable: true,
  65967. configurable: true
  65968. });
  65969. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  65970. get: function () {
  65971. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  65972. },
  65973. set: function (value) {
  65974. if (!this._physicsEngine) {
  65975. return;
  65976. }
  65977. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  65978. },
  65979. enumerable: true,
  65980. configurable: true
  65981. });
  65982. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  65983. get: function () {
  65984. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  65985. },
  65986. set: function (value) {
  65987. if (!this._physicsEngine) {
  65988. return;
  65989. }
  65990. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  65991. },
  65992. enumerable: true,
  65993. configurable: true
  65994. });
  65995. /**
  65996. * This function will completly initialize this impostor.
  65997. * It will create a new body - but only if this mesh has no parent.
  65998. * If it has, this impostor will not be used other than to define the impostor
  65999. * of the child mesh.
  66000. */
  66001. PhysicsImpostor.prototype._init = function () {
  66002. if (!this._physicsEngine) {
  66003. return;
  66004. }
  66005. this._physicsEngine.removeImpostor(this);
  66006. this.physicsBody = null;
  66007. this._parent = this._parent || this._getPhysicsParent();
  66008. if (!this.parent || this._options.ignoreParent) {
  66009. this._physicsEngine.addImpostor(this);
  66010. }
  66011. };
  66012. PhysicsImpostor.prototype._getPhysicsParent = function () {
  66013. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  66014. var parentMesh = this.object.parent;
  66015. return parentMesh.physicsImpostor;
  66016. }
  66017. return null;
  66018. };
  66019. /**
  66020. * Should a new body be generated.
  66021. */
  66022. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  66023. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  66024. };
  66025. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  66026. this.forceUpdate();
  66027. };
  66028. /**
  66029. * Force a regeneration of this or the parent's impostor's body.
  66030. * Use under cautious - This will remove all joints already implemented.
  66031. */
  66032. PhysicsImpostor.prototype.forceUpdate = function () {
  66033. this._init();
  66034. if (this.parent && !this._options.ignoreParent) {
  66035. this.parent.forceUpdate();
  66036. }
  66037. };
  66038. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  66039. /*public get mesh(): AbstractMesh {
  66040. return this._mesh;
  66041. }*/
  66042. /**
  66043. * Gets the body that holds this impostor. Either its own, or its parent.
  66044. */
  66045. get: function () {
  66046. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  66047. },
  66048. /**
  66049. * Set the physics body. Used mainly by the physics engine/plugin
  66050. */
  66051. set: function (physicsBody) {
  66052. if (this._physicsBody && this._physicsEngine) {
  66053. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  66054. }
  66055. this._physicsBody = physicsBody;
  66056. this.resetUpdateFlags();
  66057. },
  66058. enumerable: true,
  66059. configurable: true
  66060. });
  66061. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  66062. get: function () {
  66063. return !this._options.ignoreParent && this._parent ? this._parent : null;
  66064. },
  66065. set: function (value) {
  66066. this._parent = value;
  66067. },
  66068. enumerable: true,
  66069. configurable: true
  66070. });
  66071. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  66072. this._bodyUpdateRequired = false;
  66073. };
  66074. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  66075. if (this.object.getBoundingInfo) {
  66076. var q = this.object.rotationQuaternion;
  66077. //reset rotation
  66078. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  66079. //calculate the world matrix with no rotation
  66080. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  66081. var boundingInfo = this.object.getBoundingInfo();
  66082. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  66083. //bring back the rotation
  66084. this.object.rotationQuaternion = q;
  66085. //calculate the world matrix with the new rotation
  66086. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  66087. return size;
  66088. }
  66089. else {
  66090. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  66091. }
  66092. };
  66093. PhysicsImpostor.prototype.getObjectCenter = function () {
  66094. if (this.object.getBoundingInfo) {
  66095. var boundingInfo = this.object.getBoundingInfo();
  66096. return boundingInfo.boundingBox.centerWorld;
  66097. }
  66098. else {
  66099. return this.object.position;
  66100. }
  66101. };
  66102. /**
  66103. * Get a specific parametes from the options parameter.
  66104. */
  66105. PhysicsImpostor.prototype.getParam = function (paramName) {
  66106. return this._options[paramName];
  66107. };
  66108. /**
  66109. * Sets a specific parameter in the options given to the physics plugin
  66110. */
  66111. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  66112. this._options[paramName] = value;
  66113. this._bodyUpdateRequired = true;
  66114. };
  66115. /**
  66116. * Specifically change the body's mass option. Won't recreate the physics body object
  66117. */
  66118. PhysicsImpostor.prototype.setMass = function (mass) {
  66119. if (this.getParam("mass") !== mass) {
  66120. this.setParam("mass", mass);
  66121. }
  66122. if (this._physicsEngine) {
  66123. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  66124. }
  66125. };
  66126. PhysicsImpostor.prototype.getLinearVelocity = function () {
  66127. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  66128. };
  66129. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  66130. if (this._physicsEngine) {
  66131. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  66132. }
  66133. };
  66134. PhysicsImpostor.prototype.getAngularVelocity = function () {
  66135. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  66136. };
  66137. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  66138. if (this._physicsEngine) {
  66139. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  66140. }
  66141. };
  66142. /**
  66143. * Execute a function with the physics plugin native code.
  66144. * Provide a function the will have two variables - the world object and the physics body object.
  66145. */
  66146. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  66147. if (this._physicsEngine) {
  66148. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  66149. }
  66150. };
  66151. /**
  66152. * Register a function that will be executed before the physics world is stepping forward.
  66153. */
  66154. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  66155. this._onBeforePhysicsStepCallbacks.push(func);
  66156. };
  66157. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  66158. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  66159. if (index > -1) {
  66160. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  66161. }
  66162. else {
  66163. BABYLON.Tools.Warn("Function to remove was not found");
  66164. }
  66165. };
  66166. /**
  66167. * Register a function that will be executed after the physics step
  66168. */
  66169. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  66170. this._onAfterPhysicsStepCallbacks.push(func);
  66171. };
  66172. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  66173. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  66174. if (index > -1) {
  66175. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  66176. }
  66177. else {
  66178. BABYLON.Tools.Warn("Function to remove was not found");
  66179. }
  66180. };
  66181. /**
  66182. * register a function that will be executed when this impostor collides against a different body.
  66183. */
  66184. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  66185. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  66186. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  66187. };
  66188. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  66189. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  66190. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  66191. if (index > -1) {
  66192. this._onPhysicsCollideCallbacks.splice(index, 1);
  66193. }
  66194. else {
  66195. BABYLON.Tools.Warn("Function to remove was not found");
  66196. }
  66197. };
  66198. PhysicsImpostor.prototype.getParentsRotation = function () {
  66199. var parent = this.object.parent;
  66200. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  66201. while (parent) {
  66202. if (parent.rotationQuaternion) {
  66203. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  66204. }
  66205. else {
  66206. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  66207. }
  66208. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  66209. parent = parent.parent;
  66210. }
  66211. return this._tmpQuat;
  66212. };
  66213. /**
  66214. * Apply a force
  66215. */
  66216. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  66217. if (this._physicsEngine) {
  66218. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  66219. }
  66220. return this;
  66221. };
  66222. /**
  66223. * Apply an impulse
  66224. */
  66225. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  66226. if (this._physicsEngine) {
  66227. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  66228. }
  66229. return this;
  66230. };
  66231. /**
  66232. * A help function to create a joint.
  66233. */
  66234. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  66235. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  66236. this.addJoint(otherImpostor, joint);
  66237. return this;
  66238. };
  66239. /**
  66240. * Add a joint to this impostor with a different impostor.
  66241. */
  66242. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  66243. this._joints.push({
  66244. otherImpostor: otherImpostor,
  66245. joint: joint
  66246. });
  66247. if (this._physicsEngine) {
  66248. this._physicsEngine.addJoint(this, otherImpostor, joint);
  66249. }
  66250. return this;
  66251. };
  66252. /**
  66253. * Will keep this body still, in a sleep mode.
  66254. */
  66255. PhysicsImpostor.prototype.sleep = function () {
  66256. if (this._physicsEngine) {
  66257. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  66258. }
  66259. return this;
  66260. };
  66261. /**
  66262. * Wake the body up.
  66263. */
  66264. PhysicsImpostor.prototype.wakeUp = function () {
  66265. if (this._physicsEngine) {
  66266. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  66267. }
  66268. return this;
  66269. };
  66270. PhysicsImpostor.prototype.clone = function (newObject) {
  66271. if (!newObject)
  66272. return null;
  66273. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  66274. };
  66275. PhysicsImpostor.prototype.dispose = function () {
  66276. var _this = this;
  66277. //no dispose if no physics engine is available.
  66278. if (!this._physicsEngine) {
  66279. return;
  66280. }
  66281. this._joints.forEach(function (j) {
  66282. if (_this._physicsEngine) {
  66283. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  66284. }
  66285. });
  66286. //dispose the physics body
  66287. this._physicsEngine.removeImpostor(this);
  66288. if (this.parent) {
  66289. this.parent.forceUpdate();
  66290. }
  66291. else {
  66292. /*this._object.getChildMeshes().forEach(function(mesh) {
  66293. if (mesh.physicsImpostor) {
  66294. if (disposeChildren) {
  66295. mesh.physicsImpostor.dispose();
  66296. mesh.physicsImpostor = null;
  66297. }
  66298. }
  66299. })*/
  66300. }
  66301. this._isDisposed = true;
  66302. };
  66303. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  66304. this._deltaPosition.copyFrom(position);
  66305. };
  66306. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  66307. if (!this._deltaRotation) {
  66308. this._deltaRotation = new BABYLON.Quaternion();
  66309. }
  66310. this._deltaRotation.copyFrom(rotation);
  66311. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  66312. };
  66313. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  66314. if (this._physicsEngine) {
  66315. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  66316. }
  66317. return this;
  66318. };
  66319. PhysicsImpostor.prototype.getRadius = function () {
  66320. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  66321. };
  66322. /**
  66323. * Sync a bone with this impostor
  66324. * @param bone The bone to sync to the impostor.
  66325. * @param boneMesh The mesh that the bone is influencing.
  66326. * @param jointPivot The pivot of the joint / bone in local space.
  66327. * @param distToJoint Optional distance from the impostor to the joint.
  66328. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  66329. */
  66330. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  66331. var tempVec = PhysicsImpostor._tmpVecs[0];
  66332. var mesh = this.object;
  66333. if (mesh.rotationQuaternion) {
  66334. if (adjustRotation) {
  66335. var tempQuat = PhysicsImpostor._tmpQuat;
  66336. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  66337. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  66338. }
  66339. else {
  66340. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  66341. }
  66342. }
  66343. tempVec.x = 0;
  66344. tempVec.y = 0;
  66345. tempVec.z = 0;
  66346. if (jointPivot) {
  66347. tempVec.x = jointPivot.x;
  66348. tempVec.y = jointPivot.y;
  66349. tempVec.z = jointPivot.z;
  66350. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  66351. if (distToJoint === undefined || distToJoint === null) {
  66352. distToJoint = jointPivot.length();
  66353. }
  66354. tempVec.x *= distToJoint;
  66355. tempVec.y *= distToJoint;
  66356. tempVec.z *= distToJoint;
  66357. }
  66358. if (bone.getParent()) {
  66359. tempVec.addInPlace(mesh.getAbsolutePosition());
  66360. bone.setAbsolutePosition(tempVec, boneMesh);
  66361. }
  66362. else {
  66363. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  66364. boneMesh.position.x -= tempVec.x;
  66365. boneMesh.position.y -= tempVec.y;
  66366. boneMesh.position.z -= tempVec.z;
  66367. }
  66368. };
  66369. /**
  66370. * Sync impostor to a bone
  66371. * @param bone The bone that the impostor will be synced to.
  66372. * @param boneMesh The mesh that the bone is influencing.
  66373. * @param jointPivot The pivot of the joint / bone in local space.
  66374. * @param distToJoint Optional distance from the impostor to the joint.
  66375. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  66376. * @param boneAxis Optional vector3 axis the bone is aligned with
  66377. */
  66378. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  66379. var mesh = this.object;
  66380. if (mesh.rotationQuaternion) {
  66381. if (adjustRotation) {
  66382. var tempQuat = PhysicsImpostor._tmpQuat;
  66383. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  66384. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  66385. }
  66386. else {
  66387. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  66388. }
  66389. }
  66390. var pos = PhysicsImpostor._tmpVecs[0];
  66391. var boneDir = PhysicsImpostor._tmpVecs[1];
  66392. if (!boneAxis) {
  66393. boneAxis = PhysicsImpostor._tmpVecs[2];
  66394. boneAxis.x = 0;
  66395. boneAxis.y = 1;
  66396. boneAxis.z = 0;
  66397. }
  66398. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  66399. bone.getAbsolutePositionToRef(boneMesh, pos);
  66400. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  66401. distToJoint = jointPivot.length();
  66402. }
  66403. if (distToJoint !== undefined && distToJoint !== null) {
  66404. pos.x += boneDir.x * distToJoint;
  66405. pos.y += boneDir.y * distToJoint;
  66406. pos.z += boneDir.z * distToJoint;
  66407. }
  66408. mesh.setAbsolutePosition(pos);
  66409. };
  66410. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  66411. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  66412. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  66413. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  66414. //Impostor types
  66415. PhysicsImpostor.NoImpostor = 0;
  66416. PhysicsImpostor.SphereImpostor = 1;
  66417. PhysicsImpostor.BoxImpostor = 2;
  66418. PhysicsImpostor.PlaneImpostor = 3;
  66419. PhysicsImpostor.MeshImpostor = 4;
  66420. PhysicsImpostor.CylinderImpostor = 7;
  66421. PhysicsImpostor.ParticleImpostor = 8;
  66422. PhysicsImpostor.HeightmapImpostor = 9;
  66423. return PhysicsImpostor;
  66424. }());
  66425. BABYLON.PhysicsImpostor = PhysicsImpostor;
  66426. })(BABYLON || (BABYLON = {}));
  66427. //# sourceMappingURL=babylon.physicsImpostor.js.map
  66428. var BABYLON;
  66429. (function (BABYLON) {
  66430. var PhysicsEngine = /** @class */ (function () {
  66431. function PhysicsEngine(gravity, _physicsPlugin) {
  66432. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  66433. this._physicsPlugin = _physicsPlugin;
  66434. //new methods and parameters
  66435. this._impostors = [];
  66436. this._joints = [];
  66437. if (!this._physicsPlugin.isSupported()) {
  66438. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  66439. + "Please make sure it is included.");
  66440. }
  66441. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  66442. this.setGravity(gravity);
  66443. this.setTimeStep();
  66444. }
  66445. PhysicsEngine.prototype.setGravity = function (gravity) {
  66446. this.gravity = gravity;
  66447. this._physicsPlugin.setGravity(this.gravity);
  66448. };
  66449. /**
  66450. * Set the time step of the physics engine.
  66451. * default is 1/60.
  66452. * To slow it down, enter 1/600 for example.
  66453. * To speed it up, 1/30
  66454. * @param {number} newTimeStep the new timestep to apply to this world.
  66455. */
  66456. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  66457. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  66458. this._physicsPlugin.setTimeStep(newTimeStep);
  66459. };
  66460. /**
  66461. * Get the time step of the physics engine.
  66462. */
  66463. PhysicsEngine.prototype.getTimeStep = function () {
  66464. return this._physicsPlugin.getTimeStep();
  66465. };
  66466. PhysicsEngine.prototype.dispose = function () {
  66467. this._impostors.forEach(function (impostor) {
  66468. impostor.dispose();
  66469. });
  66470. this._physicsPlugin.dispose();
  66471. };
  66472. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  66473. return this._physicsPlugin.name;
  66474. };
  66475. /**
  66476. * Adding a new impostor for the impostor tracking.
  66477. * This will be done by the impostor itself.
  66478. * @param {PhysicsImpostor} impostor the impostor to add
  66479. */
  66480. PhysicsEngine.prototype.addImpostor = function (impostor) {
  66481. impostor.uniqueId = this._impostors.push(impostor);
  66482. //if no parent, generate the body
  66483. if (!impostor.parent) {
  66484. this._physicsPlugin.generatePhysicsBody(impostor);
  66485. }
  66486. };
  66487. /**
  66488. * Remove an impostor from the engine.
  66489. * This impostor and its mesh will not longer be updated by the physics engine.
  66490. * @param {PhysicsImpostor} impostor the impostor to remove
  66491. */
  66492. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  66493. var index = this._impostors.indexOf(impostor);
  66494. if (index > -1) {
  66495. var removed = this._impostors.splice(index, 1);
  66496. //Is it needed?
  66497. if (removed.length) {
  66498. //this will also remove it from the world.
  66499. removed[0].physicsBody = null;
  66500. }
  66501. }
  66502. };
  66503. /**
  66504. * Add a joint to the physics engine
  66505. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  66506. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  66507. * @param {PhysicsJoint} the joint that will connect both impostors.
  66508. */
  66509. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  66510. var impostorJoint = {
  66511. mainImpostor: mainImpostor,
  66512. connectedImpostor: connectedImpostor,
  66513. joint: joint
  66514. };
  66515. joint.physicsPlugin = this._physicsPlugin;
  66516. this._joints.push(impostorJoint);
  66517. this._physicsPlugin.generateJoint(impostorJoint);
  66518. };
  66519. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  66520. var matchingJoints = this._joints.filter(function (impostorJoint) {
  66521. return (impostorJoint.connectedImpostor === connectedImpostor
  66522. && impostorJoint.joint === joint
  66523. && impostorJoint.mainImpostor === mainImpostor);
  66524. });
  66525. if (matchingJoints.length) {
  66526. this._physicsPlugin.removeJoint(matchingJoints[0]);
  66527. //TODO remove it from the list as well
  66528. }
  66529. };
  66530. /**
  66531. * Called by the scene. no need to call it.
  66532. */
  66533. PhysicsEngine.prototype._step = function (delta) {
  66534. var _this = this;
  66535. //check if any mesh has no body / requires an update
  66536. this._impostors.forEach(function (impostor) {
  66537. if (impostor.isBodyInitRequired()) {
  66538. _this._physicsPlugin.generatePhysicsBody(impostor);
  66539. }
  66540. });
  66541. if (delta > 0.1) {
  66542. delta = 0.1;
  66543. }
  66544. else if (delta <= 0) {
  66545. delta = 1.0 / 60.0;
  66546. }
  66547. this._physicsPlugin.executeStep(delta, this._impostors);
  66548. };
  66549. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  66550. return this._physicsPlugin;
  66551. };
  66552. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  66553. for (var i = 0; i < this._impostors.length; ++i) {
  66554. if (this._impostors[i].object === object) {
  66555. return this._impostors[i];
  66556. }
  66557. }
  66558. return null;
  66559. };
  66560. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  66561. for (var i = 0; i < this._impostors.length; ++i) {
  66562. if (this._impostors[i].physicsBody === body) {
  66563. return this._impostors[i];
  66564. }
  66565. }
  66566. return null;
  66567. };
  66568. // Statics
  66569. PhysicsEngine.Epsilon = 0.001;
  66570. return PhysicsEngine;
  66571. }());
  66572. BABYLON.PhysicsEngine = PhysicsEngine;
  66573. })(BABYLON || (BABYLON = {}));
  66574. //# sourceMappingURL=babylon.physicsEngine.js.map
  66575. var BABYLON;
  66576. (function (BABYLON) {
  66577. var CannonJSPlugin = /** @class */ (function () {
  66578. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  66579. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  66580. if (iterations === void 0) { iterations = 10; }
  66581. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  66582. this.name = "CannonJSPlugin";
  66583. this._physicsMaterials = new Array();
  66584. this._fixedTimeStep = 1 / 60;
  66585. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  66586. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  66587. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  66588. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  66589. this._tmpPosition = BABYLON.Vector3.Zero();
  66590. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  66591. this._tmpUnityRotation = new BABYLON.Quaternion();
  66592. if (!this.isSupported()) {
  66593. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  66594. return;
  66595. }
  66596. this.world = new this.BJSCANNON.World();
  66597. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  66598. this.world.solver.iterations = iterations;
  66599. }
  66600. CannonJSPlugin.prototype.setGravity = function (gravity) {
  66601. this.world.gravity.copy(gravity);
  66602. };
  66603. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  66604. this._fixedTimeStep = timeStep;
  66605. };
  66606. CannonJSPlugin.prototype.getTimeStep = function () {
  66607. return this._fixedTimeStep;
  66608. };
  66609. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  66610. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  66611. };
  66612. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  66613. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  66614. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  66615. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  66616. };
  66617. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  66618. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  66619. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  66620. impostor.physicsBody.applyForce(impulse, worldPoint);
  66621. };
  66622. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  66623. //parent-child relationship. Does this impostor has a parent impostor?
  66624. if (impostor.parent) {
  66625. if (impostor.physicsBody) {
  66626. this.removePhysicsBody(impostor);
  66627. //TODO is that needed?
  66628. impostor.forceUpdate();
  66629. }
  66630. return;
  66631. }
  66632. //should a new body be created for this impostor?
  66633. if (impostor.isBodyInitRequired()) {
  66634. var shape = this._createShape(impostor);
  66635. //unregister events, if body is being changed
  66636. var oldBody = impostor.physicsBody;
  66637. if (oldBody) {
  66638. this.removePhysicsBody(impostor);
  66639. }
  66640. //create the body and material
  66641. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  66642. var bodyCreationObject = {
  66643. mass: impostor.getParam("mass"),
  66644. material: material
  66645. };
  66646. // A simple extend, in case native options were used.
  66647. var nativeOptions = impostor.getParam("nativeOptions");
  66648. for (var key in nativeOptions) {
  66649. if (nativeOptions.hasOwnProperty(key)) {
  66650. bodyCreationObject[key] = nativeOptions[key];
  66651. }
  66652. }
  66653. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  66654. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  66655. this.world.addEventListener("preStep", impostor.beforeStep);
  66656. this.world.addEventListener("postStep", impostor.afterStep);
  66657. impostor.physicsBody.addShape(shape);
  66658. this.world.add(impostor.physicsBody);
  66659. //try to keep the body moving in the right direction by taking old properties.
  66660. //Should be tested!
  66661. if (oldBody) {
  66662. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  66663. impostor.physicsBody[param].copy(oldBody[param]);
  66664. });
  66665. }
  66666. this._processChildMeshes(impostor);
  66667. }
  66668. //now update the body's transformation
  66669. this._updatePhysicsBodyTransformation(impostor);
  66670. };
  66671. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  66672. var _this = this;
  66673. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  66674. var currentRotation = mainImpostor.object.rotationQuaternion;
  66675. if (meshChildren.length) {
  66676. var processMesh = function (localPosition, mesh) {
  66677. if (!currentRotation || !mesh.rotationQuaternion) {
  66678. return;
  66679. }
  66680. var childImpostor = mesh.getPhysicsImpostor();
  66681. if (childImpostor) {
  66682. var parent = childImpostor.parent;
  66683. if (parent !== mainImpostor) {
  66684. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  66685. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  66686. if (childImpostor.physicsBody) {
  66687. _this.removePhysicsBody(childImpostor);
  66688. childImpostor.physicsBody = null;
  66689. }
  66690. childImpostor.parent = mainImpostor;
  66691. childImpostor.resetUpdateFlags();
  66692. 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));
  66693. //Add the mass of the children.
  66694. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  66695. }
  66696. }
  66697. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  66698. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  66699. };
  66700. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  66701. }
  66702. };
  66703. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  66704. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  66705. this.world.removeEventListener("preStep", impostor.beforeStep);
  66706. this.world.removeEventListener("postStep", impostor.afterStep);
  66707. this.world.remove(impostor.physicsBody);
  66708. };
  66709. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  66710. var mainBody = impostorJoint.mainImpostor.physicsBody;
  66711. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  66712. if (!mainBody || !connectedBody) {
  66713. return;
  66714. }
  66715. var constraint;
  66716. var jointData = impostorJoint.joint.jointData;
  66717. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  66718. var constraintData = {
  66719. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  66720. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  66721. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  66722. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  66723. maxForce: jointData.nativeParams.maxForce,
  66724. collideConnected: !!jointData.collision
  66725. };
  66726. switch (impostorJoint.joint.type) {
  66727. case BABYLON.PhysicsJoint.HingeJoint:
  66728. case BABYLON.PhysicsJoint.Hinge2Joint:
  66729. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  66730. break;
  66731. case BABYLON.PhysicsJoint.DistanceJoint:
  66732. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  66733. break;
  66734. case BABYLON.PhysicsJoint.SpringJoint:
  66735. var springData = jointData;
  66736. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  66737. restLength: springData.length,
  66738. stiffness: springData.stiffness,
  66739. damping: springData.damping,
  66740. localAnchorA: constraintData.pivotA,
  66741. localAnchorB: constraintData.pivotB
  66742. });
  66743. break;
  66744. case BABYLON.PhysicsJoint.LockJoint:
  66745. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  66746. break;
  66747. case BABYLON.PhysicsJoint.PointToPointJoint:
  66748. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  66749. default:
  66750. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  66751. break;
  66752. }
  66753. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  66754. constraint.collideConnected = !!jointData.collision;
  66755. impostorJoint.joint.physicsJoint = constraint;
  66756. //don't add spring as constraint, as it is not one.
  66757. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  66758. this.world.addConstraint(constraint);
  66759. }
  66760. else {
  66761. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  66762. constraint.applyForce();
  66763. });
  66764. }
  66765. };
  66766. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  66767. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  66768. };
  66769. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  66770. var index;
  66771. var mat;
  66772. for (index = 0; index < this._physicsMaterials.length; index++) {
  66773. mat = this._physicsMaterials[index];
  66774. if (mat.friction === friction && mat.restitution === restitution) {
  66775. return mat;
  66776. }
  66777. }
  66778. var currentMat = new this.BJSCANNON.Material(name);
  66779. currentMat.friction = friction;
  66780. currentMat.restitution = restitution;
  66781. this._physicsMaterials.push(currentMat);
  66782. return currentMat;
  66783. };
  66784. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  66785. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  66786. };
  66787. CannonJSPlugin.prototype._createShape = function (impostor) {
  66788. var object = impostor.object;
  66789. var returnValue;
  66790. var extendSize = impostor.getObjectExtendSize();
  66791. switch (impostor.type) {
  66792. case BABYLON.PhysicsImpostor.SphereImpostor:
  66793. var radiusX = extendSize.x;
  66794. var radiusY = extendSize.y;
  66795. var radiusZ = extendSize.z;
  66796. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  66797. break;
  66798. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  66799. case BABYLON.PhysicsImpostor.CylinderImpostor:
  66800. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  66801. break;
  66802. case BABYLON.PhysicsImpostor.BoxImpostor:
  66803. var box = extendSize.scale(0.5);
  66804. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  66805. break;
  66806. case BABYLON.PhysicsImpostor.PlaneImpostor:
  66807. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  66808. returnValue = new this.BJSCANNON.Plane();
  66809. break;
  66810. case BABYLON.PhysicsImpostor.MeshImpostor:
  66811. // should transform the vertex data to world coordinates!!
  66812. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  66813. var rawFaces = object.getIndices ? object.getIndices() : [];
  66814. if (!rawVerts)
  66815. return;
  66816. // get only scale! so the object could transform correctly.
  66817. var oldPosition = object.position.clone();
  66818. var oldRotation = object.rotation && object.rotation.clone();
  66819. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  66820. object.position.copyFromFloats(0, 0, 0);
  66821. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  66822. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  66823. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  66824. var transform = object.computeWorldMatrix(true);
  66825. // convert rawVerts to object space
  66826. var temp = new Array();
  66827. var index;
  66828. for (index = 0; index < rawVerts.length; index += 3) {
  66829. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  66830. }
  66831. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  66832. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  66833. //now set back the transformation!
  66834. object.position.copyFrom(oldPosition);
  66835. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  66836. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  66837. break;
  66838. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  66839. var oldPosition2 = object.position.clone();
  66840. var oldRotation2 = object.rotation && object.rotation.clone();
  66841. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  66842. object.position.copyFromFloats(0, 0, 0);
  66843. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  66844. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  66845. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  66846. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  66847. returnValue = this._createHeightmap(object);
  66848. object.position.copyFrom(oldPosition2);
  66849. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  66850. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  66851. object.computeWorldMatrix(true);
  66852. break;
  66853. case BABYLON.PhysicsImpostor.ParticleImpostor:
  66854. returnValue = new this.BJSCANNON.Particle();
  66855. break;
  66856. }
  66857. return returnValue;
  66858. };
  66859. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  66860. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  66861. var transform = object.computeWorldMatrix(true);
  66862. // convert rawVerts to object space
  66863. var temp = new Array();
  66864. var index;
  66865. for (index = 0; index < pos.length; index += 3) {
  66866. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  66867. }
  66868. pos = temp;
  66869. var matrix = new Array();
  66870. //For now pointDepth will not be used and will be automatically calculated.
  66871. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  66872. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  66873. var boundingInfo = object.getBoundingInfo();
  66874. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  66875. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  66876. var elementSize = dim * 2 / arraySize;
  66877. for (var i = 0; i < pos.length; i = i + 3) {
  66878. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  66879. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  66880. var y = -pos[i + 2] + minY;
  66881. if (!matrix[x]) {
  66882. matrix[x] = [];
  66883. }
  66884. if (!matrix[x][z]) {
  66885. matrix[x][z] = y;
  66886. }
  66887. matrix[x][z] = Math.max(y, matrix[x][z]);
  66888. }
  66889. for (var x = 0; x <= arraySize; ++x) {
  66890. if (!matrix[x]) {
  66891. var loc = 1;
  66892. while (!matrix[(x + loc) % arraySize]) {
  66893. loc++;
  66894. }
  66895. matrix[x] = matrix[(x + loc) % arraySize].slice();
  66896. //console.log("missing x", x);
  66897. }
  66898. for (var z = 0; z <= arraySize; ++z) {
  66899. if (!matrix[x][z]) {
  66900. var loc = 1;
  66901. var newValue;
  66902. while (newValue === undefined) {
  66903. newValue = matrix[x][(z + loc++) % arraySize];
  66904. }
  66905. matrix[x][z] = newValue;
  66906. }
  66907. }
  66908. }
  66909. var shape = new this.BJSCANNON.Heightfield(matrix, {
  66910. elementSize: elementSize
  66911. });
  66912. //For future reference, needed for body transformation
  66913. shape.minY = minY;
  66914. return shape;
  66915. };
  66916. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  66917. var object = impostor.object;
  66918. //make sure it is updated...
  66919. object.computeWorldMatrix && object.computeWorldMatrix(true);
  66920. // The delta between the mesh position and the mesh bounding box center
  66921. var bInfo = object.getBoundingInfo();
  66922. if (!bInfo)
  66923. return;
  66924. var center = impostor.getObjectCenter();
  66925. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  66926. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  66927. this._tmpPosition.copyFrom(center);
  66928. var quaternion = object.rotationQuaternion;
  66929. if (!quaternion) {
  66930. return;
  66931. }
  66932. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  66933. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  66934. //-90 DEG in X, precalculated
  66935. quaternion = quaternion.multiply(this._minus90X);
  66936. //Invert! (Precalculated, 90 deg in X)
  66937. //No need to clone. this will never change.
  66938. impostor.setDeltaRotation(this._plus90X);
  66939. }
  66940. //If it is a heightfield, if should be centered.
  66941. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  66942. var mesh = object;
  66943. var boundingInfo = mesh.getBoundingInfo();
  66944. //calculate the correct body position:
  66945. var rotationQuaternion = mesh.rotationQuaternion;
  66946. mesh.rotationQuaternion = this._tmpUnityRotation;
  66947. mesh.computeWorldMatrix(true);
  66948. //get original center with no rotation
  66949. var c = center.clone();
  66950. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  66951. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  66952. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  66953. mesh.setPivotMatrix(p);
  66954. mesh.computeWorldMatrix(true);
  66955. //calculate the translation
  66956. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  66957. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  66958. //add it inverted to the delta
  66959. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  66960. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  66961. //rotation is back
  66962. mesh.rotationQuaternion = rotationQuaternion;
  66963. mesh.setPivotMatrix(oldPivot);
  66964. mesh.computeWorldMatrix(true);
  66965. }
  66966. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  66967. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  66968. //this._tmpPosition.copyFrom(object.position);
  66969. }
  66970. impostor.setDeltaPosition(this._tmpDeltaPosition);
  66971. //Now update the impostor object
  66972. impostor.physicsBody.position.copy(this._tmpPosition);
  66973. impostor.physicsBody.quaternion.copy(quaternion);
  66974. };
  66975. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  66976. impostor.object.position.copyFrom(impostor.physicsBody.position);
  66977. if (impostor.object.rotationQuaternion) {
  66978. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  66979. }
  66980. };
  66981. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  66982. impostor.physicsBody.position.copy(newPosition);
  66983. impostor.physicsBody.quaternion.copy(newRotation);
  66984. };
  66985. CannonJSPlugin.prototype.isSupported = function () {
  66986. return this.BJSCANNON !== undefined;
  66987. };
  66988. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  66989. impostor.physicsBody.velocity.copy(velocity);
  66990. };
  66991. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  66992. impostor.physicsBody.angularVelocity.copy(velocity);
  66993. };
  66994. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  66995. var v = impostor.physicsBody.velocity;
  66996. if (!v) {
  66997. return null;
  66998. }
  66999. return new BABYLON.Vector3(v.x, v.y, v.z);
  67000. };
  67001. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  67002. var v = impostor.physicsBody.angularVelocity;
  67003. if (!v) {
  67004. return null;
  67005. }
  67006. return new BABYLON.Vector3(v.x, v.y, v.z);
  67007. };
  67008. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  67009. impostor.physicsBody.mass = mass;
  67010. impostor.physicsBody.updateMassProperties();
  67011. };
  67012. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  67013. return impostor.physicsBody.mass;
  67014. };
  67015. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  67016. return impostor.physicsBody.material.friction;
  67017. };
  67018. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  67019. impostor.physicsBody.material.friction = friction;
  67020. };
  67021. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  67022. return impostor.physicsBody.material.restitution;
  67023. };
  67024. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  67025. impostor.physicsBody.material.restitution = restitution;
  67026. };
  67027. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  67028. impostor.physicsBody.sleep();
  67029. };
  67030. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  67031. impostor.physicsBody.wakeUp();
  67032. };
  67033. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  67034. joint.physicsJoint.distance = maxDistance;
  67035. };
  67036. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  67037. // if (!motorIndex) {
  67038. // joint.physicsJoint.enableMotor();
  67039. // }
  67040. // }
  67041. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  67042. // if (!motorIndex) {
  67043. // joint.physicsJoint.disableMotor();
  67044. // }
  67045. // }
  67046. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  67047. if (!motorIndex) {
  67048. joint.physicsJoint.enableMotor();
  67049. joint.physicsJoint.setMotorSpeed(speed);
  67050. if (maxForce) {
  67051. this.setLimit(joint, maxForce);
  67052. }
  67053. }
  67054. };
  67055. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  67056. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  67057. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  67058. };
  67059. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  67060. var body = impostor.physicsBody;
  67061. mesh.position.x = body.position.x;
  67062. mesh.position.y = body.position.y;
  67063. mesh.position.z = body.position.z;
  67064. if (mesh.rotationQuaternion) {
  67065. mesh.rotationQuaternion.x = body.quaternion.x;
  67066. mesh.rotationQuaternion.y = body.quaternion.y;
  67067. mesh.rotationQuaternion.z = body.quaternion.z;
  67068. mesh.rotationQuaternion.w = body.quaternion.w;
  67069. }
  67070. };
  67071. CannonJSPlugin.prototype.getRadius = function (impostor) {
  67072. var shape = impostor.physicsBody.shapes[0];
  67073. return shape.boundingSphereRadius;
  67074. };
  67075. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  67076. var shape = impostor.physicsBody.shapes[0];
  67077. result.x = shape.halfExtents.x * 2;
  67078. result.y = shape.halfExtents.y * 2;
  67079. result.z = shape.halfExtents.z * 2;
  67080. };
  67081. CannonJSPlugin.prototype.dispose = function () {
  67082. };
  67083. return CannonJSPlugin;
  67084. }());
  67085. BABYLON.CannonJSPlugin = CannonJSPlugin;
  67086. })(BABYLON || (BABYLON = {}));
  67087. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  67088. var BABYLON;
  67089. (function (BABYLON) {
  67090. var OimoJSPlugin = /** @class */ (function () {
  67091. function OimoJSPlugin(iterations) {
  67092. this.name = "OimoJSPlugin";
  67093. this._tmpImpostorsArray = [];
  67094. this._tmpPositionVector = BABYLON.Vector3.Zero();
  67095. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  67096. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  67097. this.world.worldscale(1);
  67098. this.world.clear();
  67099. //making sure no stats are calculated
  67100. this.world.isNoStat = true;
  67101. }
  67102. OimoJSPlugin.prototype.setGravity = function (gravity) {
  67103. this.world.gravity.copy(gravity);
  67104. };
  67105. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  67106. this.world.timeStep = timeStep;
  67107. };
  67108. OimoJSPlugin.prototype.getTimeStep = function () {
  67109. return this.world.timeStep;
  67110. };
  67111. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  67112. var _this = this;
  67113. impostors.forEach(function (impostor) {
  67114. impostor.beforeStep();
  67115. });
  67116. this.world.step();
  67117. impostors.forEach(function (impostor) {
  67118. impostor.afterStep();
  67119. //update the ordered impostors array
  67120. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  67121. });
  67122. //check for collisions
  67123. var contact = this.world.contacts;
  67124. while (contact !== null) {
  67125. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  67126. contact = contact.next;
  67127. continue;
  67128. }
  67129. //is this body colliding with any other? get the impostor
  67130. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  67131. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  67132. if (!mainImpostor || !collidingImpostor) {
  67133. contact = contact.next;
  67134. continue;
  67135. }
  67136. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  67137. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  67138. contact = contact.next;
  67139. }
  67140. };
  67141. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  67142. var mass = impostor.physicsBody.massInfo.mass;
  67143. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  67144. };
  67145. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  67146. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  67147. this.applyImpulse(impostor, force, contactPoint);
  67148. };
  67149. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  67150. var _this = this;
  67151. //parent-child relationship. Does this impostor has a parent impostor?
  67152. if (impostor.parent) {
  67153. if (impostor.physicsBody) {
  67154. this.removePhysicsBody(impostor);
  67155. //TODO is that needed?
  67156. impostor.forceUpdate();
  67157. }
  67158. return;
  67159. }
  67160. if (impostor.isBodyInitRequired()) {
  67161. var bodyConfig = {
  67162. name: impostor.uniqueId,
  67163. //Oimo must have mass, also for static objects.
  67164. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  67165. size: [],
  67166. type: [],
  67167. pos: [],
  67168. rot: [],
  67169. move: impostor.getParam("mass") !== 0,
  67170. //Supporting older versions of Oimo
  67171. world: this.world
  67172. };
  67173. var impostors = [impostor];
  67174. var addToArray = function (parent) {
  67175. if (!parent.getChildMeshes)
  67176. return;
  67177. parent.getChildMeshes().forEach(function (m) {
  67178. if (m.physicsImpostor) {
  67179. impostors.push(m.physicsImpostor);
  67180. //m.physicsImpostor._init();
  67181. }
  67182. });
  67183. };
  67184. addToArray(impostor.object);
  67185. var checkWithEpsilon_1 = function (value) {
  67186. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  67187. };
  67188. impostors.forEach(function (i) {
  67189. if (!impostor.object.rotationQuaternion) {
  67190. return;
  67191. }
  67192. //get the correct bounding box
  67193. var oldQuaternion = i.object.rotationQuaternion;
  67194. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  67195. x: impostor.object.rotationQuaternion.x,
  67196. y: impostor.object.rotationQuaternion.y,
  67197. z: impostor.object.rotationQuaternion.z,
  67198. s: impostor.object.rotationQuaternion.w
  67199. });
  67200. var extendSize = i.getObjectExtendSize();
  67201. if (i === impostor) {
  67202. var center = impostor.getObjectCenter();
  67203. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  67204. //Can also use Array.prototype.push.apply
  67205. bodyConfig.pos.push(center.x);
  67206. bodyConfig.pos.push(center.y);
  67207. bodyConfig.pos.push(center.z);
  67208. //tmp solution
  67209. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  67210. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  67211. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  67212. }
  67213. else {
  67214. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  67215. bodyConfig.pos.push(localPosition.x);
  67216. bodyConfig.pos.push(localPosition.y);
  67217. bodyConfig.pos.push(localPosition.z);
  67218. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  67219. bodyConfig.rot.push(0);
  67220. bodyConfig.rot.push(0);
  67221. bodyConfig.rot.push(0);
  67222. }
  67223. // register mesh
  67224. switch (i.type) {
  67225. case BABYLON.PhysicsImpostor.ParticleImpostor:
  67226. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  67227. case BABYLON.PhysicsImpostor.SphereImpostor:
  67228. var radiusX = extendSize.x;
  67229. var radiusY = extendSize.y;
  67230. var radiusZ = extendSize.z;
  67231. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  67232. bodyConfig.type.push('sphere');
  67233. //due to the way oimo works with compounds, add 3 times
  67234. bodyConfig.size.push(size);
  67235. bodyConfig.size.push(size);
  67236. bodyConfig.size.push(size);
  67237. break;
  67238. case BABYLON.PhysicsImpostor.CylinderImpostor:
  67239. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  67240. var sizeY = checkWithEpsilon_1(extendSize.y);
  67241. bodyConfig.type.push('cylinder');
  67242. bodyConfig.size.push(sizeX);
  67243. bodyConfig.size.push(sizeY);
  67244. //due to the way oimo works with compounds, add one more value.
  67245. bodyConfig.size.push(sizeY);
  67246. break;
  67247. case BABYLON.PhysicsImpostor.PlaneImpostor:
  67248. case BABYLON.PhysicsImpostor.BoxImpostor:
  67249. default:
  67250. var sizeX = checkWithEpsilon_1(extendSize.x);
  67251. var sizeY = checkWithEpsilon_1(extendSize.y);
  67252. var sizeZ = checkWithEpsilon_1(extendSize.z);
  67253. bodyConfig.type.push('box');
  67254. bodyConfig.size.push(sizeX);
  67255. bodyConfig.size.push(sizeY);
  67256. bodyConfig.size.push(sizeZ);
  67257. break;
  67258. }
  67259. //actually not needed, but hey...
  67260. i.object.rotationQuaternion = oldQuaternion;
  67261. });
  67262. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  67263. }
  67264. else {
  67265. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  67266. }
  67267. impostor.setDeltaPosition(this._tmpPositionVector);
  67268. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  67269. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  67270. };
  67271. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  67272. //impostor.physicsBody.dispose();
  67273. //Same as : (older oimo versions)
  67274. this.world.removeRigidBody(impostor.physicsBody);
  67275. };
  67276. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  67277. var mainBody = impostorJoint.mainImpostor.physicsBody;
  67278. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  67279. if (!mainBody || !connectedBody) {
  67280. return;
  67281. }
  67282. var jointData = impostorJoint.joint.jointData;
  67283. var options = jointData.nativeParams || {};
  67284. var type;
  67285. var nativeJointData = {
  67286. body1: mainBody,
  67287. body2: connectedBody,
  67288. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  67289. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  67290. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  67291. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  67292. min: options.min,
  67293. max: options.max,
  67294. collision: options.collision || jointData.collision,
  67295. spring: options.spring,
  67296. //supporting older version of Oimo
  67297. world: this.world
  67298. };
  67299. switch (impostorJoint.joint.type) {
  67300. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  67301. type = "jointBall";
  67302. break;
  67303. case BABYLON.PhysicsJoint.SpringJoint:
  67304. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  67305. var springData = jointData;
  67306. nativeJointData.min = springData.length || nativeJointData.min;
  67307. //Max should also be set, just make sure it is at least min
  67308. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  67309. case BABYLON.PhysicsJoint.DistanceJoint:
  67310. type = "jointDistance";
  67311. nativeJointData.max = jointData.maxDistance;
  67312. break;
  67313. case BABYLON.PhysicsJoint.PrismaticJoint:
  67314. type = "jointPrisme";
  67315. break;
  67316. case BABYLON.PhysicsJoint.SliderJoint:
  67317. type = "jointSlide";
  67318. break;
  67319. case BABYLON.PhysicsJoint.WheelJoint:
  67320. type = "jointWheel";
  67321. break;
  67322. case BABYLON.PhysicsJoint.HingeJoint:
  67323. default:
  67324. type = "jointHinge";
  67325. break;
  67326. }
  67327. nativeJointData.type = type;
  67328. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  67329. };
  67330. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  67331. //Bug in Oimo prevents us from disposing a joint in the playground
  67332. //joint.joint.physicsJoint.dispose();
  67333. //So we will bruteforce it!
  67334. try {
  67335. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  67336. }
  67337. catch (e) {
  67338. BABYLON.Tools.Warn(e);
  67339. }
  67340. };
  67341. OimoJSPlugin.prototype.isSupported = function () {
  67342. return this.BJSOIMO !== undefined;
  67343. };
  67344. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  67345. if (!impostor.physicsBody.sleeping) {
  67346. //TODO check that
  67347. if (impostor.physicsBody.shapes.next) {
  67348. var parentShape = this._getLastShape(impostor.physicsBody);
  67349. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  67350. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  67351. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  67352. }
  67353. else {
  67354. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  67355. }
  67356. if (impostor.object.rotationQuaternion) {
  67357. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  67358. impostor.object.rotationQuaternion.normalize();
  67359. }
  67360. }
  67361. };
  67362. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  67363. var body = impostor.physicsBody;
  67364. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  67365. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  67366. body.syncShapes();
  67367. body.awake();
  67368. };
  67369. OimoJSPlugin.prototype._getLastShape = function (body) {
  67370. var lastShape = body.shapes;
  67371. while (lastShape.next) {
  67372. lastShape = lastShape.next;
  67373. }
  67374. return lastShape;
  67375. };
  67376. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  67377. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  67378. };
  67379. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  67380. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  67381. };
  67382. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  67383. var v = impostor.physicsBody.linearVelocity;
  67384. if (!v) {
  67385. return null;
  67386. }
  67387. return new BABYLON.Vector3(v.x, v.y, v.z);
  67388. };
  67389. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  67390. var v = impostor.physicsBody.angularVelocity;
  67391. if (!v) {
  67392. return null;
  67393. }
  67394. return new BABYLON.Vector3(v.x, v.y, v.z);
  67395. };
  67396. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  67397. var staticBody = mass === 0;
  67398. //this will actually set the body's density and not its mass.
  67399. //But this is how oimo treats the mass variable.
  67400. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  67401. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  67402. };
  67403. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  67404. return impostor.physicsBody.shapes.density;
  67405. };
  67406. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  67407. return impostor.physicsBody.shapes.friction;
  67408. };
  67409. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  67410. impostor.physicsBody.shapes.friction = friction;
  67411. };
  67412. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  67413. return impostor.physicsBody.shapes.restitution;
  67414. };
  67415. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  67416. impostor.physicsBody.shapes.restitution = restitution;
  67417. };
  67418. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  67419. impostor.physicsBody.sleep();
  67420. };
  67421. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  67422. impostor.physicsBody.awake();
  67423. };
  67424. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  67425. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  67426. if (minDistance !== void 0) {
  67427. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  67428. }
  67429. };
  67430. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  67431. //TODO separate rotational and transational motors.
  67432. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  67433. if (motor) {
  67434. motor.setMotor(speed, maxForce);
  67435. }
  67436. };
  67437. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  67438. //TODO separate rotational and transational motors.
  67439. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  67440. if (motor) {
  67441. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  67442. }
  67443. };
  67444. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  67445. var body = impostor.physicsBody;
  67446. mesh.position.x = body.position.x;
  67447. mesh.position.y = body.position.y;
  67448. mesh.position.z = body.position.z;
  67449. if (mesh.rotationQuaternion) {
  67450. mesh.rotationQuaternion.x = body.orientation.x;
  67451. mesh.rotationQuaternion.y = body.orientation.y;
  67452. mesh.rotationQuaternion.z = body.orientation.z;
  67453. mesh.rotationQuaternion.w = body.orientation.s;
  67454. }
  67455. };
  67456. OimoJSPlugin.prototype.getRadius = function (impostor) {
  67457. return impostor.physicsBody.shapes.radius;
  67458. };
  67459. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  67460. var shape = impostor.physicsBody.shapes;
  67461. result.x = shape.halfWidth * 2;
  67462. result.y = shape.halfHeight * 2;
  67463. result.z = shape.halfDepth * 2;
  67464. };
  67465. OimoJSPlugin.prototype.dispose = function () {
  67466. this.world.clear();
  67467. };
  67468. return OimoJSPlugin;
  67469. }());
  67470. BABYLON.OimoJSPlugin = OimoJSPlugin;
  67471. })(BABYLON || (BABYLON = {}));
  67472. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  67473. var BABYLON;
  67474. (function (BABYLON) {
  67475. var Internals;
  67476. (function (Internals) {
  67477. /*
  67478. * Based on jsTGALoader - Javascript loader for TGA file
  67479. * By Vincent Thibault
  67480. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  67481. */
  67482. var TGATools = /** @class */ (function () {
  67483. function TGATools() {
  67484. }
  67485. TGATools.GetTGAHeader = function (data) {
  67486. var offset = 0;
  67487. var header = {
  67488. id_length: data[offset++],
  67489. colormap_type: data[offset++],
  67490. image_type: data[offset++],
  67491. colormap_index: data[offset++] | data[offset++] << 8,
  67492. colormap_length: data[offset++] | data[offset++] << 8,
  67493. colormap_size: data[offset++],
  67494. origin: [
  67495. data[offset++] | data[offset++] << 8,
  67496. data[offset++] | data[offset++] << 8
  67497. ],
  67498. width: data[offset++] | data[offset++] << 8,
  67499. height: data[offset++] | data[offset++] << 8,
  67500. pixel_size: data[offset++],
  67501. flags: data[offset++]
  67502. };
  67503. return header;
  67504. };
  67505. TGATools.UploadContent = function (gl, data) {
  67506. // Not enough data to contain header ?
  67507. if (data.length < 19) {
  67508. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  67509. return;
  67510. }
  67511. // Read Header
  67512. var offset = 18;
  67513. var header = TGATools.GetTGAHeader(data);
  67514. // Assume it's a valid Targa file.
  67515. if (header.id_length + offset > data.length) {
  67516. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  67517. return;
  67518. }
  67519. // Skip not needed data
  67520. offset += header.id_length;
  67521. var use_rle = false;
  67522. var use_pal = false;
  67523. var use_grey = false;
  67524. // Get some informations.
  67525. switch (header.image_type) {
  67526. case TGATools._TYPE_RLE_INDEXED:
  67527. use_rle = true;
  67528. case TGATools._TYPE_INDEXED:
  67529. use_pal = true;
  67530. break;
  67531. case TGATools._TYPE_RLE_RGB:
  67532. use_rle = true;
  67533. case TGATools._TYPE_RGB:
  67534. // use_rgb = true;
  67535. break;
  67536. case TGATools._TYPE_RLE_GREY:
  67537. use_rle = true;
  67538. case TGATools._TYPE_GREY:
  67539. use_grey = true;
  67540. break;
  67541. }
  67542. var pixel_data;
  67543. // var numAlphaBits = header.flags & 0xf;
  67544. var pixel_size = header.pixel_size >> 3;
  67545. var pixel_total = header.width * header.height * pixel_size;
  67546. // Read palettes
  67547. var palettes;
  67548. if (use_pal) {
  67549. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  67550. }
  67551. // Read LRE
  67552. if (use_rle) {
  67553. pixel_data = new Uint8Array(pixel_total);
  67554. var c, count, i;
  67555. var localOffset = 0;
  67556. var pixels = new Uint8Array(pixel_size);
  67557. while (offset < pixel_total && localOffset < pixel_total) {
  67558. c = data[offset++];
  67559. count = (c & 0x7f) + 1;
  67560. // RLE pixels
  67561. if (c & 0x80) {
  67562. // Bind pixel tmp array
  67563. for (i = 0; i < pixel_size; ++i) {
  67564. pixels[i] = data[offset++];
  67565. }
  67566. // Copy pixel array
  67567. for (i = 0; i < count; ++i) {
  67568. pixel_data.set(pixels, localOffset + i * pixel_size);
  67569. }
  67570. localOffset += pixel_size * count;
  67571. }
  67572. else {
  67573. count *= pixel_size;
  67574. for (i = 0; i < count; ++i) {
  67575. pixel_data[localOffset + i] = data[offset++];
  67576. }
  67577. localOffset += count;
  67578. }
  67579. }
  67580. }
  67581. else {
  67582. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  67583. }
  67584. // Load to texture
  67585. var x_start, y_start, x_step, y_step, y_end, x_end;
  67586. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  67587. default:
  67588. case TGATools._ORIGIN_UL:
  67589. x_start = 0;
  67590. x_step = 1;
  67591. x_end = header.width;
  67592. y_start = 0;
  67593. y_step = 1;
  67594. y_end = header.height;
  67595. break;
  67596. case TGATools._ORIGIN_BL:
  67597. x_start = 0;
  67598. x_step = 1;
  67599. x_end = header.width;
  67600. y_start = header.height - 1;
  67601. y_step = -1;
  67602. y_end = -1;
  67603. break;
  67604. case TGATools._ORIGIN_UR:
  67605. x_start = header.width - 1;
  67606. x_step = -1;
  67607. x_end = -1;
  67608. y_start = 0;
  67609. y_step = 1;
  67610. y_end = header.height;
  67611. break;
  67612. case TGATools._ORIGIN_BR:
  67613. x_start = header.width - 1;
  67614. x_step = -1;
  67615. x_end = -1;
  67616. y_start = header.height - 1;
  67617. y_step = -1;
  67618. y_end = -1;
  67619. break;
  67620. }
  67621. // Load the specify method
  67622. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  67623. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  67624. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  67625. };
  67626. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67627. var image = pixel_data, colormap = palettes;
  67628. var width = header.width, height = header.height;
  67629. var color, i = 0, x, y;
  67630. var imageData = new Uint8Array(width * height * 4);
  67631. for (y = y_start; y !== y_end; y += y_step) {
  67632. for (x = x_start; x !== x_end; x += x_step, i++) {
  67633. color = image[i];
  67634. imageData[(x + width * y) * 4 + 3] = 255;
  67635. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  67636. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  67637. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  67638. }
  67639. }
  67640. return imageData;
  67641. };
  67642. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67643. var image = pixel_data;
  67644. var width = header.width, height = header.height;
  67645. var color, i = 0, x, y;
  67646. var imageData = new Uint8Array(width * height * 4);
  67647. for (y = y_start; y !== y_end; y += y_step) {
  67648. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  67649. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  67650. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  67651. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  67652. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  67653. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  67654. }
  67655. }
  67656. return imageData;
  67657. };
  67658. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67659. var image = pixel_data;
  67660. var width = header.width, height = header.height;
  67661. var i = 0, x, y;
  67662. var imageData = new Uint8Array(width * height * 4);
  67663. for (y = y_start; y !== y_end; y += y_step) {
  67664. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  67665. imageData[(x + width * y) * 4 + 3] = 255;
  67666. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  67667. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  67668. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  67669. }
  67670. }
  67671. return imageData;
  67672. };
  67673. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67674. var image = pixel_data;
  67675. var width = header.width, height = header.height;
  67676. var i = 0, x, y;
  67677. var imageData = new Uint8Array(width * height * 4);
  67678. for (y = y_start; y !== y_end; y += y_step) {
  67679. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  67680. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  67681. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  67682. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  67683. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  67684. }
  67685. }
  67686. return imageData;
  67687. };
  67688. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67689. var image = pixel_data;
  67690. var width = header.width, height = header.height;
  67691. var color, i = 0, x, y;
  67692. var imageData = new Uint8Array(width * height * 4);
  67693. for (y = y_start; y !== y_end; y += y_step) {
  67694. for (x = x_start; x !== x_end; x += x_step, i++) {
  67695. color = image[i];
  67696. imageData[(x + width * y) * 4 + 0] = color;
  67697. imageData[(x + width * y) * 4 + 1] = color;
  67698. imageData[(x + width * y) * 4 + 2] = color;
  67699. imageData[(x + width * y) * 4 + 3] = 255;
  67700. }
  67701. }
  67702. return imageData;
  67703. };
  67704. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67705. var image = pixel_data;
  67706. var width = header.width, height = header.height;
  67707. var i = 0, x, y;
  67708. var imageData = new Uint8Array(width * height * 4);
  67709. for (y = y_start; y !== y_end; y += y_step) {
  67710. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  67711. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  67712. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  67713. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  67714. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  67715. }
  67716. }
  67717. return imageData;
  67718. };
  67719. //private static _TYPE_NO_DATA = 0;
  67720. TGATools._TYPE_INDEXED = 1;
  67721. TGATools._TYPE_RGB = 2;
  67722. TGATools._TYPE_GREY = 3;
  67723. TGATools._TYPE_RLE_INDEXED = 9;
  67724. TGATools._TYPE_RLE_RGB = 10;
  67725. TGATools._TYPE_RLE_GREY = 11;
  67726. TGATools._ORIGIN_MASK = 0x30;
  67727. TGATools._ORIGIN_SHIFT = 0x04;
  67728. TGATools._ORIGIN_BL = 0x00;
  67729. TGATools._ORIGIN_BR = 0x01;
  67730. TGATools._ORIGIN_UL = 0x02;
  67731. TGATools._ORIGIN_UR = 0x03;
  67732. return TGATools;
  67733. }());
  67734. Internals.TGATools = TGATools;
  67735. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  67736. })(BABYLON || (BABYLON = {}));
  67737. //# sourceMappingURL=babylon.tga.js.map
  67738. var BABYLON;
  67739. (function (BABYLON) {
  67740. var Internals;
  67741. (function (Internals) {
  67742. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  67743. // All values and structures referenced from:
  67744. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  67745. var DDS_MAGIC = 0x20534444;
  67746. var
  67747. //DDSD_CAPS = 0x1,
  67748. //DDSD_HEIGHT = 0x2,
  67749. //DDSD_WIDTH = 0x4,
  67750. //DDSD_PITCH = 0x8,
  67751. //DDSD_PIXELFORMAT = 0x1000,
  67752. DDSD_MIPMAPCOUNT = 0x20000;
  67753. //DDSD_LINEARSIZE = 0x80000,
  67754. //DDSD_DEPTH = 0x800000;
  67755. // var DDSCAPS_COMPLEX = 0x8,
  67756. // DDSCAPS_MIPMAP = 0x400000,
  67757. // DDSCAPS_TEXTURE = 0x1000;
  67758. var DDSCAPS2_CUBEMAP = 0x200;
  67759. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  67760. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  67761. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  67762. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  67763. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  67764. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  67765. // DDSCAPS2_VOLUME = 0x200000;
  67766. var
  67767. //DDPF_ALPHAPIXELS = 0x1,
  67768. //DDPF_ALPHA = 0x2,
  67769. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  67770. //DDPF_YUV = 0x200,
  67771. DDPF_LUMINANCE = 0x20000;
  67772. function FourCCToInt32(value) {
  67773. return value.charCodeAt(0) +
  67774. (value.charCodeAt(1) << 8) +
  67775. (value.charCodeAt(2) << 16) +
  67776. (value.charCodeAt(3) << 24);
  67777. }
  67778. function Int32ToFourCC(value) {
  67779. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  67780. }
  67781. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  67782. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  67783. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  67784. var FOURCC_DX10 = FourCCToInt32("DX10");
  67785. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  67786. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  67787. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  67788. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  67789. var headerLengthInt = 31; // The header length in 32 bit ints
  67790. // Offsets into the header array
  67791. var off_magic = 0;
  67792. var off_size = 1;
  67793. var off_flags = 2;
  67794. var off_height = 3;
  67795. var off_width = 4;
  67796. var off_mipmapCount = 7;
  67797. var off_pfFlags = 20;
  67798. var off_pfFourCC = 21;
  67799. var off_RGBbpp = 22;
  67800. // var off_RMask = 23;
  67801. // var off_GMask = 24;
  67802. // var off_BMask = 25;
  67803. // var off_AMask = 26;
  67804. // var off_caps1 = 27;
  67805. var off_caps2 = 28;
  67806. // var off_caps3 = 29;
  67807. // var off_caps4 = 30;
  67808. var off_dxgiFormat = 32;
  67809. ;
  67810. var DDSTools = /** @class */ (function () {
  67811. function DDSTools() {
  67812. }
  67813. DDSTools.GetDDSInfo = function (arrayBuffer) {
  67814. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  67815. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  67816. var mipmapCount = 1;
  67817. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  67818. mipmapCount = Math.max(1, header[off_mipmapCount]);
  67819. }
  67820. var fourCC = header[off_pfFourCC];
  67821. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  67822. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67823. switch (fourCC) {
  67824. case FOURCC_D3DFMT_R16G16B16A16F:
  67825. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67826. break;
  67827. case FOURCC_D3DFMT_R32G32B32A32F:
  67828. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67829. break;
  67830. case FOURCC_DX10:
  67831. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  67832. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67833. break;
  67834. }
  67835. }
  67836. return {
  67837. width: header[off_width],
  67838. height: header[off_height],
  67839. mipmapCount: mipmapCount,
  67840. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  67841. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  67842. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  67843. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  67844. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  67845. dxgiFormat: dxgiFormat,
  67846. textureType: textureType
  67847. };
  67848. };
  67849. DDSTools._ToHalfFloat = function (value) {
  67850. if (!DDSTools._FloatView) {
  67851. DDSTools._FloatView = new Float32Array(1);
  67852. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  67853. }
  67854. DDSTools._FloatView[0] = value;
  67855. var x = DDSTools._Int32View[0];
  67856. var bits = (x >> 16) & 0x8000; /* Get the sign */
  67857. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  67858. var e = (x >> 23) & 0xff; /* Using int is faster here */
  67859. /* If zero, or denormal, or exponent underflows too much for a denormal
  67860. * half, return signed zero. */
  67861. if (e < 103) {
  67862. return bits;
  67863. }
  67864. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  67865. if (e > 142) {
  67866. bits |= 0x7c00;
  67867. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  67868. * not Inf, so make sure we set one mantissa bit too. */
  67869. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  67870. return bits;
  67871. }
  67872. /* If exponent underflows but not too much, return a denormal */
  67873. if (e < 113) {
  67874. m |= 0x0800;
  67875. /* Extra rounding may overflow and set mantissa to 0 and exponent
  67876. * to 1, which is OK. */
  67877. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  67878. return bits;
  67879. }
  67880. bits |= ((e - 112) << 10) | (m >> 1);
  67881. bits += m & 1;
  67882. return bits;
  67883. };
  67884. DDSTools._FromHalfFloat = function (value) {
  67885. var s = (value & 0x8000) >> 15;
  67886. var e = (value & 0x7C00) >> 10;
  67887. var f = value & 0x03FF;
  67888. if (e === 0) {
  67889. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  67890. }
  67891. else if (e == 0x1F) {
  67892. return f ? NaN : ((s ? -1 : 1) * Infinity);
  67893. }
  67894. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  67895. };
  67896. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67897. var destArray = new Float32Array(dataLength);
  67898. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  67899. var index = 0;
  67900. for (var y = 0; y < height; y++) {
  67901. for (var x = 0; x < width; x++) {
  67902. var srcPos = (x + y * width) * 4;
  67903. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  67904. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  67905. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  67906. if (DDSTools.StoreLODInAlphaChannel) {
  67907. destArray[index + 3] = lod;
  67908. }
  67909. else {
  67910. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  67911. }
  67912. index += 4;
  67913. }
  67914. }
  67915. return destArray;
  67916. };
  67917. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67918. if (DDSTools.StoreLODInAlphaChannel) {
  67919. var destArray = new Uint16Array(dataLength);
  67920. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  67921. var index = 0;
  67922. for (var y = 0; y < height; y++) {
  67923. for (var x = 0; x < width; x++) {
  67924. var srcPos = (x + y * width) * 4;
  67925. destArray[index] = srcData[srcPos];
  67926. destArray[index + 1] = srcData[srcPos + 1];
  67927. destArray[index + 2] = srcData[srcPos + 2];
  67928. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  67929. index += 4;
  67930. }
  67931. }
  67932. return destArray;
  67933. }
  67934. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  67935. };
  67936. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67937. if (DDSTools.StoreLODInAlphaChannel) {
  67938. var destArray = new Float32Array(dataLength);
  67939. var srcData = new Float32Array(arrayBuffer, dataOffset);
  67940. var index = 0;
  67941. for (var y = 0; y < height; y++) {
  67942. for (var x = 0; x < width; x++) {
  67943. var srcPos = (x + y * width) * 4;
  67944. destArray[index] = srcData[srcPos];
  67945. destArray[index + 1] = srcData[srcPos + 1];
  67946. destArray[index + 2] = srcData[srcPos + 2];
  67947. destArray[index + 3] = lod;
  67948. index += 4;
  67949. }
  67950. }
  67951. return destArray;
  67952. }
  67953. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  67954. };
  67955. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67956. var destArray = new Uint8Array(dataLength);
  67957. var srcData = new Float32Array(arrayBuffer, dataOffset);
  67958. var index = 0;
  67959. for (var y = 0; y < height; y++) {
  67960. for (var x = 0; x < width; x++) {
  67961. var srcPos = (x + y * width) * 4;
  67962. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  67963. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  67964. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  67965. if (DDSTools.StoreLODInAlphaChannel) {
  67966. destArray[index + 3] = lod;
  67967. }
  67968. else {
  67969. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  67970. }
  67971. index += 4;
  67972. }
  67973. }
  67974. return destArray;
  67975. };
  67976. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67977. var destArray = new Uint8Array(dataLength);
  67978. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  67979. var index = 0;
  67980. for (var y = 0; y < height; y++) {
  67981. for (var x = 0; x < width; x++) {
  67982. var srcPos = (x + y * width) * 4;
  67983. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  67984. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  67985. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  67986. if (DDSTools.StoreLODInAlphaChannel) {
  67987. destArray[index + 3] = lod;
  67988. }
  67989. else {
  67990. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  67991. }
  67992. index += 4;
  67993. }
  67994. }
  67995. return destArray;
  67996. };
  67997. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67998. var byteArray = new Uint8Array(dataLength);
  67999. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  68000. var index = 0;
  68001. for (var y = 0; y < height; y++) {
  68002. for (var x = 0; x < width; x++) {
  68003. var srcPos = (x + y * width) * 4;
  68004. byteArray[index] = srcData[srcPos + 2];
  68005. byteArray[index + 1] = srcData[srcPos + 1];
  68006. byteArray[index + 2] = srcData[srcPos];
  68007. byteArray[index + 3] = srcData[srcPos + 3];
  68008. index += 4;
  68009. }
  68010. }
  68011. return byteArray;
  68012. };
  68013. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  68014. var byteArray = new Uint8Array(dataLength);
  68015. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  68016. var index = 0;
  68017. for (var y = 0; y < height; y++) {
  68018. for (var x = 0; x < width; x++) {
  68019. var srcPos = (x + y * width) * 3;
  68020. byteArray[index] = srcData[srcPos + 2];
  68021. byteArray[index + 1] = srcData[srcPos + 1];
  68022. byteArray[index + 2] = srcData[srcPos];
  68023. index += 3;
  68024. }
  68025. }
  68026. return byteArray;
  68027. };
  68028. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  68029. var byteArray = new Uint8Array(dataLength);
  68030. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  68031. var index = 0;
  68032. for (var y = 0; y < height; y++) {
  68033. for (var x = 0; x < width; x++) {
  68034. var srcPos = (x + y * width);
  68035. byteArray[index] = srcData[srcPos];
  68036. index++;
  68037. }
  68038. }
  68039. return byteArray;
  68040. };
  68041. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  68042. if (lodIndex === void 0) { lodIndex = -1; }
  68043. var ext = engine.getCaps().s3tc;
  68044. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  68045. var fourCC, width, height, dataLength = 0, dataOffset;
  68046. var byteArray, mipmapCount, mip;
  68047. var internalFormat = 0;
  68048. var format = 0;
  68049. var blockBytes = 1;
  68050. if (header[off_magic] !== DDS_MAGIC) {
  68051. BABYLON.Tools.Error("Invalid magic number in DDS header");
  68052. return;
  68053. }
  68054. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  68055. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  68056. return;
  68057. }
  68058. if (info.isCompressed && !ext) {
  68059. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  68060. return;
  68061. }
  68062. var bpp = header[off_RGBbpp];
  68063. dataOffset = header[off_size] + 4;
  68064. var computeFormats = false;
  68065. if (info.isFourCC) {
  68066. fourCC = header[off_pfFourCC];
  68067. switch (fourCC) {
  68068. case FOURCC_DXT1:
  68069. blockBytes = 8;
  68070. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  68071. break;
  68072. case FOURCC_DXT3:
  68073. blockBytes = 16;
  68074. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  68075. break;
  68076. case FOURCC_DXT5:
  68077. blockBytes = 16;
  68078. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  68079. break;
  68080. case FOURCC_D3DFMT_R16G16B16A16F:
  68081. computeFormats = true;
  68082. break;
  68083. case FOURCC_D3DFMT_R32G32B32A32F:
  68084. computeFormats = true;
  68085. break;
  68086. case FOURCC_DX10:
  68087. // There is an additionnal header so dataOffset need to be changed
  68088. dataOffset += 5 * 4; // 5 uints
  68089. var supported = false;
  68090. switch (info.dxgiFormat) {
  68091. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  68092. computeFormats = true;
  68093. supported = true;
  68094. break;
  68095. case DXGI_FORMAT_B8G8R8X8_UNORM:
  68096. info.isRGB = true;
  68097. info.isFourCC = false;
  68098. bpp = 32;
  68099. supported = true;
  68100. break;
  68101. }
  68102. if (supported) {
  68103. break;
  68104. }
  68105. default:
  68106. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  68107. return;
  68108. }
  68109. }
  68110. if (computeFormats) {
  68111. format = engine._getWebGLTextureType(info.textureType);
  68112. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  68113. }
  68114. mipmapCount = 1;
  68115. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  68116. mipmapCount = Math.max(1, header[off_mipmapCount]);
  68117. }
  68118. for (var face = 0; face < faces; face++) {
  68119. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  68120. width = header[off_width];
  68121. height = header[off_height];
  68122. for (mip = 0; mip < mipmapCount; ++mip) {
  68123. if (lodIndex === -1 || lodIndex === mip) {
  68124. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  68125. var i = (lodIndex === -1) ? mip : 0;
  68126. if (!info.isCompressed && info.isFourCC) {
  68127. dataLength = width * height * 4;
  68128. var floatArray = null;
  68129. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  68130. if (bpp === 128) {
  68131. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  68132. }
  68133. else if (bpp === 64) {
  68134. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  68135. }
  68136. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68137. format = engine._getWebGLTextureType(info.textureType);
  68138. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  68139. }
  68140. else {
  68141. if (bpp === 128) {
  68142. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  68143. }
  68144. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  68145. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  68146. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68147. format = engine._getWebGLTextureType(info.textureType);
  68148. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  68149. }
  68150. else {
  68151. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  68152. }
  68153. }
  68154. if (floatArray) {
  68155. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  68156. }
  68157. }
  68158. else if (info.isRGB) {
  68159. if (bpp === 24) {
  68160. dataLength = width * height * 3;
  68161. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  68162. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  68163. }
  68164. else {
  68165. dataLength = width * height * 4;
  68166. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  68167. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  68168. }
  68169. }
  68170. else if (info.isLuminance) {
  68171. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  68172. var unpaddedRowSize = width;
  68173. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  68174. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  68175. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  68176. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  68177. }
  68178. else {
  68179. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  68180. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  68181. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  68182. }
  68183. }
  68184. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  68185. width *= 0.5;
  68186. height *= 0.5;
  68187. width = Math.max(1.0, width);
  68188. height = Math.max(1.0, height);
  68189. }
  68190. if (currentFace !== undefined) {
  68191. // Loading a single face
  68192. break;
  68193. }
  68194. }
  68195. };
  68196. DDSTools.StoreLODInAlphaChannel = false;
  68197. return DDSTools;
  68198. }());
  68199. Internals.DDSTools = DDSTools;
  68200. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  68201. })(BABYLON || (BABYLON = {}));
  68202. //# sourceMappingURL=babylon.dds.js.map
  68203. var BABYLON;
  68204. (function (BABYLON) {
  68205. var Internals;
  68206. (function (Internals) {
  68207. /**
  68208. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  68209. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  68210. */
  68211. var KhronosTextureContainer = /** @class */ (function () {
  68212. /**
  68213. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  68214. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  68215. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  68216. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  68217. */
  68218. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  68219. this.arrayBuffer = arrayBuffer;
  68220. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  68221. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  68222. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  68223. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  68224. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  68225. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  68226. BABYLON.Tools.Error("texture missing KTX identifier");
  68227. return;
  68228. }
  68229. // load the reset of the header in native 32 bit int
  68230. var header = new Int32Array(this.arrayBuffer, 12, 13);
  68231. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  68232. var oppositeEndianess = header[0] === 0x01020304;
  68233. // read all the header elements in order they exist in the file, without modification (sans endainness)
  68234. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  68235. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  68236. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  68237. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  68238. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  68239. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  68240. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  68241. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  68242. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  68243. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  68244. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  68245. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  68246. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  68247. if (this.glType !== 0) {
  68248. BABYLON.Tools.Error("only compressed formats currently supported");
  68249. return;
  68250. }
  68251. else {
  68252. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  68253. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  68254. }
  68255. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  68256. BABYLON.Tools.Error("only 2D textures currently supported");
  68257. return;
  68258. }
  68259. if (this.numberOfArrayElements !== 0) {
  68260. BABYLON.Tools.Error("texture arrays not currently supported");
  68261. return;
  68262. }
  68263. if (this.numberOfFaces !== facesExpected) {
  68264. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  68265. return;
  68266. }
  68267. // we now have a completely validated file, so could use existence of loadType as success
  68268. // would need to make this more elaborate & adjust checks above to support more than one load type
  68269. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  68270. }
  68271. // not as fast hardware based, but will probably never need to use
  68272. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  68273. return ((val & 0xFF) << 24)
  68274. | ((val & 0xFF00) << 8)
  68275. | ((val >> 8) & 0xFF00)
  68276. | ((val >> 24) & 0xFF);
  68277. };
  68278. /**
  68279. * It is assumed that the texture has already been created & is currently bound
  68280. */
  68281. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  68282. switch (this.loadType) {
  68283. case KhronosTextureContainer.COMPRESSED_2D:
  68284. this._upload2DCompressedLevels(gl, loadMipmaps);
  68285. break;
  68286. case KhronosTextureContainer.TEX_2D:
  68287. case KhronosTextureContainer.COMPRESSED_3D:
  68288. case KhronosTextureContainer.TEX_3D:
  68289. }
  68290. };
  68291. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  68292. // initialize width & height for level 1
  68293. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  68294. var width = this.pixelWidth;
  68295. var height = this.pixelHeight;
  68296. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  68297. for (var level = 0; level < mipmapCount; level++) {
  68298. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  68299. for (var face = 0; face < this.numberOfFaces; face++) {
  68300. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  68301. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  68302. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  68303. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  68304. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  68305. }
  68306. width = Math.max(1.0, width * 0.5);
  68307. height = Math.max(1.0, height * 0.5);
  68308. }
  68309. };
  68310. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  68311. // load types
  68312. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  68313. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  68314. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  68315. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  68316. return KhronosTextureContainer;
  68317. }());
  68318. Internals.KhronosTextureContainer = KhronosTextureContainer;
  68319. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  68320. })(BABYLON || (BABYLON = {}));
  68321. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  68322. var BABYLON;
  68323. (function (BABYLON) {
  68324. var Debug;
  68325. (function (Debug) {
  68326. /**
  68327. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  68328. */
  68329. var SkeletonViewer = /** @class */ (function () {
  68330. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  68331. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  68332. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  68333. this.skeleton = skeleton;
  68334. this.mesh = mesh;
  68335. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  68336. this.renderingGroupId = renderingGroupId;
  68337. this.color = BABYLON.Color3.White();
  68338. this._debugLines = new Array();
  68339. this._isEnabled = false;
  68340. this._scene = scene;
  68341. this.update();
  68342. this._renderFunction = this.update.bind(this);
  68343. }
  68344. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  68345. get: function () {
  68346. return this._isEnabled;
  68347. },
  68348. set: function (value) {
  68349. if (this._isEnabled === value) {
  68350. return;
  68351. }
  68352. this._isEnabled = value;
  68353. if (value) {
  68354. this._scene.registerBeforeRender(this._renderFunction);
  68355. }
  68356. else {
  68357. this._scene.unregisterBeforeRender(this._renderFunction);
  68358. }
  68359. },
  68360. enumerable: true,
  68361. configurable: true
  68362. });
  68363. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  68364. if (x === void 0) { x = 0; }
  68365. if (y === void 0) { y = 0; }
  68366. if (z === void 0) { z = 0; }
  68367. var tmat = BABYLON.Tmp.Matrix[0];
  68368. var parentBone = bone.getParent();
  68369. tmat.copyFrom(bone.getLocalMatrix());
  68370. if (x !== 0 || y !== 0 || z !== 0) {
  68371. var tmat2 = BABYLON.Tmp.Matrix[1];
  68372. BABYLON.Matrix.IdentityToRef(tmat2);
  68373. tmat2.m[12] = x;
  68374. tmat2.m[13] = y;
  68375. tmat2.m[14] = z;
  68376. tmat2.multiplyToRef(tmat, tmat);
  68377. }
  68378. if (parentBone) {
  68379. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  68380. }
  68381. tmat.multiplyToRef(meshMat, tmat);
  68382. position.x = tmat.m[12];
  68383. position.y = tmat.m[13];
  68384. position.z = tmat.m[14];
  68385. };
  68386. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  68387. var len = bones.length;
  68388. var meshPos = this.mesh.position;
  68389. for (var i = 0; i < len; i++) {
  68390. var bone = bones[i];
  68391. var points = this._debugLines[i];
  68392. if (!points) {
  68393. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  68394. this._debugLines[i] = points;
  68395. }
  68396. this._getBonePosition(points[0], bone, meshMat);
  68397. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  68398. points[0].subtractInPlace(meshPos);
  68399. points[1].subtractInPlace(meshPos);
  68400. }
  68401. };
  68402. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  68403. var len = bones.length;
  68404. var boneNum = 0;
  68405. var meshPos = this.mesh.position;
  68406. for (var i = len - 1; i >= 0; i--) {
  68407. var childBone = bones[i];
  68408. var parentBone = childBone.getParent();
  68409. if (!parentBone) {
  68410. continue;
  68411. }
  68412. var points = this._debugLines[boneNum];
  68413. if (!points) {
  68414. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  68415. this._debugLines[boneNum] = points;
  68416. }
  68417. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  68418. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  68419. points[0].subtractInPlace(meshPos);
  68420. points[1].subtractInPlace(meshPos);
  68421. boneNum++;
  68422. }
  68423. };
  68424. SkeletonViewer.prototype.update = function () {
  68425. if (this.autoUpdateBonesMatrices) {
  68426. this.skeleton.computeAbsoluteTransforms();
  68427. }
  68428. if (this.skeleton.bones[0].length === undefined) {
  68429. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  68430. }
  68431. else {
  68432. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  68433. }
  68434. if (!this._debugMesh) {
  68435. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  68436. this._debugMesh.renderingGroupId = this.renderingGroupId;
  68437. }
  68438. else {
  68439. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  68440. }
  68441. this._debugMesh.position.copyFrom(this.mesh.position);
  68442. this._debugMesh.color = this.color;
  68443. };
  68444. SkeletonViewer.prototype.dispose = function () {
  68445. if (this._debugMesh) {
  68446. this.isEnabled = false;
  68447. this._debugMesh.dispose();
  68448. this._debugMesh = null;
  68449. }
  68450. };
  68451. return SkeletonViewer;
  68452. }());
  68453. Debug.SkeletonViewer = SkeletonViewer;
  68454. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  68455. })(BABYLON || (BABYLON = {}));
  68456. //# sourceMappingURL=babylon.skeletonViewer.js.map
  68457. var BABYLON;
  68458. (function (BABYLON) {
  68459. var Debug;
  68460. (function (Debug) {
  68461. var AxesViewer = /** @class */ (function () {
  68462. function AxesViewer(scene, scaleLines) {
  68463. if (scaleLines === void 0) { scaleLines = 1; }
  68464. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  68465. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  68466. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  68467. this.scaleLines = 1;
  68468. this.scaleLines = scaleLines;
  68469. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  68470. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  68471. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  68472. this._xmesh.renderingGroupId = 2;
  68473. this._ymesh.renderingGroupId = 2;
  68474. this._zmesh.renderingGroupId = 2;
  68475. this._xmesh.material.checkReadyOnlyOnce = true;
  68476. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  68477. this._ymesh.material.checkReadyOnlyOnce = true;
  68478. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  68479. this._zmesh.material.checkReadyOnlyOnce = true;
  68480. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  68481. this.scene = scene;
  68482. }
  68483. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  68484. var scaleLines = this.scaleLines;
  68485. if (this._xmesh) {
  68486. this._xmesh.position.copyFrom(position);
  68487. }
  68488. if (this._ymesh) {
  68489. this._ymesh.position.copyFrom(position);
  68490. }
  68491. if (this._zmesh) {
  68492. this._zmesh.position.copyFrom(position);
  68493. }
  68494. var point2 = this._xline[1];
  68495. point2.x = xaxis.x * scaleLines;
  68496. point2.y = xaxis.y * scaleLines;
  68497. point2.z = xaxis.z * scaleLines;
  68498. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  68499. point2 = this._yline[1];
  68500. point2.x = yaxis.x * scaleLines;
  68501. point2.y = yaxis.y * scaleLines;
  68502. point2.z = yaxis.z * scaleLines;
  68503. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  68504. point2 = this._zline[1];
  68505. point2.x = zaxis.x * scaleLines;
  68506. point2.y = zaxis.y * scaleLines;
  68507. point2.z = zaxis.z * scaleLines;
  68508. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  68509. };
  68510. AxesViewer.prototype.dispose = function () {
  68511. if (this._xmesh) {
  68512. this._xmesh.dispose();
  68513. }
  68514. if (this._ymesh) {
  68515. this._ymesh.dispose();
  68516. }
  68517. if (this._zmesh) {
  68518. this._zmesh.dispose();
  68519. }
  68520. this._xmesh = null;
  68521. this._ymesh = null;
  68522. this._zmesh = null;
  68523. this.scene = null;
  68524. };
  68525. return AxesViewer;
  68526. }());
  68527. Debug.AxesViewer = AxesViewer;
  68528. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  68529. })(BABYLON || (BABYLON = {}));
  68530. //# sourceMappingURL=babylon.axesViewer.js.map
  68531. var BABYLON;
  68532. (function (BABYLON) {
  68533. var Debug;
  68534. (function (Debug) {
  68535. var BoneAxesViewer = /** @class */ (function (_super) {
  68536. __extends(BoneAxesViewer, _super);
  68537. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  68538. if (scaleLines === void 0) { scaleLines = 1; }
  68539. var _this = _super.call(this, scene, scaleLines) || this;
  68540. _this.pos = BABYLON.Vector3.Zero();
  68541. _this.xaxis = BABYLON.Vector3.Zero();
  68542. _this.yaxis = BABYLON.Vector3.Zero();
  68543. _this.zaxis = BABYLON.Vector3.Zero();
  68544. _this.mesh = mesh;
  68545. _this.bone = bone;
  68546. return _this;
  68547. }
  68548. BoneAxesViewer.prototype.update = function () {
  68549. if (!this.mesh || !this.bone) {
  68550. return;
  68551. }
  68552. var bone = this.bone;
  68553. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  68554. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  68555. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  68556. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  68557. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  68558. };
  68559. BoneAxesViewer.prototype.dispose = function () {
  68560. if (this.mesh) {
  68561. this.mesh = null;
  68562. this.bone = null;
  68563. _super.prototype.dispose.call(this);
  68564. }
  68565. };
  68566. return BoneAxesViewer;
  68567. }(Debug.AxesViewer));
  68568. Debug.BoneAxesViewer = BoneAxesViewer;
  68569. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  68570. })(BABYLON || (BABYLON = {}));
  68571. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  68572. var BABYLON;
  68573. (function (BABYLON) {
  68574. var RayHelper = /** @class */ (function () {
  68575. function RayHelper(ray) {
  68576. this.ray = ray;
  68577. }
  68578. RayHelper.CreateAndShow = function (ray, scene, color) {
  68579. var helper = new RayHelper(ray);
  68580. helper.show(scene, color);
  68581. return helper;
  68582. };
  68583. RayHelper.prototype.show = function (scene, color) {
  68584. if (!this._renderFunction && this.ray) {
  68585. var ray = this.ray;
  68586. this._renderFunction = this._render.bind(this);
  68587. this._scene = scene;
  68588. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  68589. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  68590. if (this._renderFunction) {
  68591. this._scene.registerBeforeRender(this._renderFunction);
  68592. }
  68593. }
  68594. if (color && this._renderLine) {
  68595. this._renderLine.color.copyFrom(color);
  68596. }
  68597. };
  68598. RayHelper.prototype.hide = function () {
  68599. if (this._renderFunction && this._scene) {
  68600. this._scene.unregisterBeforeRender(this._renderFunction);
  68601. this._scene = null;
  68602. this._renderFunction = null;
  68603. if (this._renderLine) {
  68604. this._renderLine.dispose();
  68605. this._renderLine = null;
  68606. }
  68607. this._renderPoints = [];
  68608. }
  68609. };
  68610. RayHelper.prototype._render = function () {
  68611. var ray = this.ray;
  68612. if (!ray) {
  68613. return;
  68614. }
  68615. var point = this._renderPoints[1];
  68616. var len = Math.min(ray.length, 1000000);
  68617. point.copyFrom(ray.direction);
  68618. point.scaleInPlace(len);
  68619. point.addInPlace(ray.origin);
  68620. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  68621. };
  68622. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  68623. this._attachedToMesh = mesh;
  68624. var ray = this.ray;
  68625. if (!ray) {
  68626. return;
  68627. }
  68628. if (!ray.direction) {
  68629. ray.direction = BABYLON.Vector3.Zero();
  68630. }
  68631. if (!ray.origin) {
  68632. ray.origin = BABYLON.Vector3.Zero();
  68633. }
  68634. if (length) {
  68635. ray.length = length;
  68636. }
  68637. if (!meshSpaceOrigin) {
  68638. meshSpaceOrigin = BABYLON.Vector3.Zero();
  68639. }
  68640. if (!meshSpaceDirection) {
  68641. // -1 so that this will work with Mesh.lookAt
  68642. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  68643. }
  68644. if (!this._meshSpaceDirection) {
  68645. this._meshSpaceDirection = meshSpaceDirection.clone();
  68646. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  68647. }
  68648. else {
  68649. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  68650. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  68651. }
  68652. if (!this._updateToMeshFunction) {
  68653. this._updateToMeshFunction = this._updateToMesh.bind(this);
  68654. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  68655. }
  68656. this._updateToMesh();
  68657. };
  68658. RayHelper.prototype.detachFromMesh = function () {
  68659. if (this._attachedToMesh) {
  68660. if (this._updateToMeshFunction) {
  68661. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  68662. }
  68663. this._attachedToMesh = null;
  68664. this._updateToMeshFunction = null;
  68665. }
  68666. };
  68667. RayHelper.prototype._updateToMesh = function () {
  68668. var ray = this.ray;
  68669. if (!this._attachedToMesh || !ray) {
  68670. return;
  68671. }
  68672. if (this._attachedToMesh._isDisposed) {
  68673. this.detachFromMesh();
  68674. return;
  68675. }
  68676. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  68677. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  68678. };
  68679. RayHelper.prototype.dispose = function () {
  68680. this.hide();
  68681. this.detachFromMesh();
  68682. this.ray = null;
  68683. };
  68684. return RayHelper;
  68685. }());
  68686. BABYLON.RayHelper = RayHelper;
  68687. })(BABYLON || (BABYLON = {}));
  68688. //# sourceMappingURL=babylon.rayHelper.js.map
  68689. var BABYLON;
  68690. (function (BABYLON) {
  68691. // load the inspector using require, if not present in the global namespace.
  68692. var DebugLayer = /** @class */ (function () {
  68693. function DebugLayer(scene) {
  68694. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  68695. this._scene = scene;
  68696. // load inspector using require, if it doesn't exist on the global namespace.
  68697. }
  68698. /** Creates the inspector window. */
  68699. DebugLayer.prototype._createInspector = function (config) {
  68700. if (config === void 0) { config = {}; }
  68701. var popup = config.popup || false;
  68702. var initialTab = config.initialTab || 0;
  68703. var parentElement = config.parentElement || null;
  68704. if (!this._inspector) {
  68705. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  68706. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  68707. } // else nothing to do,; instance is already existing
  68708. };
  68709. DebugLayer.prototype.isVisible = function () {
  68710. if (!this._inspector) {
  68711. return false;
  68712. }
  68713. return true;
  68714. };
  68715. DebugLayer.prototype.hide = function () {
  68716. if (this._inspector) {
  68717. try {
  68718. this._inspector.dispose();
  68719. }
  68720. catch (e) {
  68721. // If the inspector has been removed directly from the inspector tool
  68722. }
  68723. this._inspector = null;
  68724. }
  68725. };
  68726. DebugLayer.prototype.show = function (config) {
  68727. if (config === void 0) { config = {}; }
  68728. if (typeof this.BJSINSPECTOR == 'undefined') {
  68729. // Load inspector and add it to the DOM
  68730. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  68731. }
  68732. else {
  68733. // Otherwise creates the inspector
  68734. this._createInspector(config);
  68735. }
  68736. };
  68737. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  68738. return DebugLayer;
  68739. }());
  68740. BABYLON.DebugLayer = DebugLayer;
  68741. })(BABYLON || (BABYLON = {}));
  68742. //# sourceMappingURL=babylon.debugLayer.js.map
  68743. var BABYLON;
  68744. (function (BABYLON) {
  68745. var Debug;
  68746. (function (Debug) {
  68747. var PhysicsViewer = /** @class */ (function () {
  68748. function PhysicsViewer(scene) {
  68749. this._impostors = [];
  68750. this._meshes = [];
  68751. this._numMeshes = 0;
  68752. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  68753. var physicEngine = this._scene.getPhysicsEngine();
  68754. if (physicEngine) {
  68755. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  68756. }
  68757. }
  68758. PhysicsViewer.prototype._updateDebugMeshes = function () {
  68759. var plugin = this._physicsEnginePlugin;
  68760. for (var i = 0; i < this._numMeshes; i++) {
  68761. var impostor = this._impostors[i];
  68762. if (!impostor) {
  68763. continue;
  68764. }
  68765. if (impostor.isDisposed) {
  68766. this.hideImpostor(this._impostors[i--]);
  68767. }
  68768. else {
  68769. var mesh = this._meshes[i];
  68770. if (mesh && plugin) {
  68771. plugin.syncMeshWithImpostor(mesh, impostor);
  68772. }
  68773. }
  68774. }
  68775. };
  68776. PhysicsViewer.prototype.showImpostor = function (impostor) {
  68777. if (!this._scene) {
  68778. return;
  68779. }
  68780. for (var i = 0; i < this._numMeshes; i++) {
  68781. if (this._impostors[i] == impostor) {
  68782. return;
  68783. }
  68784. }
  68785. var debugMesh = this._getDebugMesh(impostor, this._scene);
  68786. if (debugMesh) {
  68787. this._impostors[this._numMeshes] = impostor;
  68788. this._meshes[this._numMeshes] = debugMesh;
  68789. if (this._numMeshes === 0) {
  68790. this._renderFunction = this._updateDebugMeshes.bind(this);
  68791. this._scene.registerBeforeRender(this._renderFunction);
  68792. }
  68793. this._numMeshes++;
  68794. }
  68795. };
  68796. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  68797. if (!impostor || !this._scene) {
  68798. return;
  68799. }
  68800. var removed = false;
  68801. for (var i = 0; i < this._numMeshes; i++) {
  68802. if (this._impostors[i] == impostor) {
  68803. var mesh = this._meshes[i];
  68804. if (!mesh) {
  68805. continue;
  68806. }
  68807. this._scene.removeMesh(mesh);
  68808. mesh.dispose();
  68809. this._numMeshes--;
  68810. if (this._numMeshes > 0) {
  68811. this._meshes[i] = this._meshes[this._numMeshes];
  68812. this._impostors[i] = this._impostors[this._numMeshes];
  68813. this._meshes[this._numMeshes] = null;
  68814. this._impostors[this._numMeshes] = null;
  68815. }
  68816. else {
  68817. this._meshes[0] = null;
  68818. this._impostors[0] = null;
  68819. }
  68820. removed = true;
  68821. break;
  68822. }
  68823. }
  68824. if (removed && this._numMeshes === 0) {
  68825. this._scene.unregisterBeforeRender(this._renderFunction);
  68826. }
  68827. };
  68828. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  68829. if (!this._debugMaterial) {
  68830. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  68831. this._debugMaterial.wireframe = true;
  68832. }
  68833. return this._debugMaterial;
  68834. };
  68835. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  68836. if (!this._debugBoxMesh) {
  68837. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  68838. this._debugBoxMesh.renderingGroupId = 1;
  68839. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  68840. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  68841. scene.removeMesh(this._debugBoxMesh);
  68842. }
  68843. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  68844. };
  68845. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  68846. if (!this._debugSphereMesh) {
  68847. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  68848. this._debugSphereMesh.renderingGroupId = 1;
  68849. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  68850. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  68851. scene.removeMesh(this._debugSphereMesh);
  68852. }
  68853. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  68854. };
  68855. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  68856. var mesh = null;
  68857. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  68858. mesh = this._getDebugBoxMesh(scene);
  68859. impostor.getBoxSizeToRef(mesh.scaling);
  68860. }
  68861. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  68862. mesh = this._getDebugSphereMesh(scene);
  68863. var radius = impostor.getRadius();
  68864. mesh.scaling.x = radius * 2;
  68865. mesh.scaling.y = radius * 2;
  68866. mesh.scaling.z = radius * 2;
  68867. }
  68868. return mesh;
  68869. };
  68870. PhysicsViewer.prototype.dispose = function () {
  68871. for (var i = 0; i < this._numMeshes; i++) {
  68872. this.hideImpostor(this._impostors[i]);
  68873. }
  68874. if (this._debugBoxMesh) {
  68875. this._debugBoxMesh.dispose();
  68876. }
  68877. if (this._debugSphereMesh) {
  68878. this._debugSphereMesh.dispose();
  68879. }
  68880. if (this._debugMaterial) {
  68881. this._debugMaterial.dispose();
  68882. }
  68883. this._impostors.length = 0;
  68884. this._scene = null;
  68885. this._physicsEnginePlugin = null;
  68886. };
  68887. return PhysicsViewer;
  68888. }());
  68889. Debug.PhysicsViewer = PhysicsViewer;
  68890. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  68891. })(BABYLON || (BABYLON = {}));
  68892. //# sourceMappingURL=babylon.physicsViewer.js.map
  68893. var BABYLON;
  68894. (function (BABYLON) {
  68895. var BoundingBoxRenderer = /** @class */ (function () {
  68896. function BoundingBoxRenderer(scene) {
  68897. this.frontColor = new BABYLON.Color3(1, 1, 1);
  68898. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  68899. this.showBackLines = true;
  68900. this.renderList = new BABYLON.SmartArray(32);
  68901. this._vertexBuffers = {};
  68902. this._scene = scene;
  68903. }
  68904. BoundingBoxRenderer.prototype._prepareRessources = function () {
  68905. if (this._colorShader) {
  68906. return;
  68907. }
  68908. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  68909. attributes: [BABYLON.VertexBuffer.PositionKind],
  68910. uniforms: ["world", "viewProjection", "color"]
  68911. });
  68912. var engine = this._scene.getEngine();
  68913. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  68914. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  68915. this._createIndexBuffer();
  68916. };
  68917. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  68918. var engine = this._scene.getEngine();
  68919. 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]);
  68920. };
  68921. BoundingBoxRenderer.prototype._rebuild = function () {
  68922. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68923. if (vb) {
  68924. vb._rebuild();
  68925. }
  68926. this._createIndexBuffer();
  68927. };
  68928. BoundingBoxRenderer.prototype.reset = function () {
  68929. this.renderList.reset();
  68930. };
  68931. BoundingBoxRenderer.prototype.render = function () {
  68932. if (this.renderList.length === 0) {
  68933. return;
  68934. }
  68935. this._prepareRessources();
  68936. if (!this._colorShader.isReady()) {
  68937. return;
  68938. }
  68939. var engine = this._scene.getEngine();
  68940. engine.setDepthWrite(false);
  68941. this._colorShader._preBind();
  68942. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  68943. var boundingBox = this.renderList.data[boundingBoxIndex];
  68944. var min = boundingBox.minimum;
  68945. var max = boundingBox.maximum;
  68946. var diff = max.subtract(min);
  68947. var median = min.add(diff.scale(0.5));
  68948. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  68949. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  68950. .multiply(boundingBox.getWorldMatrix());
  68951. // VBOs
  68952. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  68953. if (this.showBackLines) {
  68954. // Back
  68955. engine.setDepthFunctionToGreaterOrEqual();
  68956. this._scene.resetCachedMaterial();
  68957. this._colorShader.setColor4("color", this.backColor.toColor4());
  68958. this._colorShader.bind(worldMatrix);
  68959. // Draw order
  68960. engine.draw(false, 0, 24);
  68961. }
  68962. // Front
  68963. engine.setDepthFunctionToLess();
  68964. this._scene.resetCachedMaterial();
  68965. this._colorShader.setColor4("color", this.frontColor.toColor4());
  68966. this._colorShader.bind(worldMatrix);
  68967. // Draw order
  68968. engine.draw(false, 0, 24);
  68969. }
  68970. this._colorShader.unbind();
  68971. engine.setDepthFunctionToLessOrEqual();
  68972. engine.setDepthWrite(true);
  68973. };
  68974. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  68975. this._prepareRessources();
  68976. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  68977. return;
  68978. }
  68979. var engine = this._scene.getEngine();
  68980. engine.setDepthWrite(false);
  68981. engine.setColorWrite(false);
  68982. this._colorShader._preBind();
  68983. var boundingBox = mesh._boundingInfo.boundingBox;
  68984. var min = boundingBox.minimum;
  68985. var max = boundingBox.maximum;
  68986. var diff = max.subtract(min);
  68987. var median = min.add(diff.scale(0.5));
  68988. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  68989. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  68990. .multiply(boundingBox.getWorldMatrix());
  68991. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  68992. engine.setDepthFunctionToLess();
  68993. this._scene.resetCachedMaterial();
  68994. this._colorShader.bind(worldMatrix);
  68995. engine.draw(false, 0, 24);
  68996. this._colorShader.unbind();
  68997. engine.setDepthFunctionToLessOrEqual();
  68998. engine.setDepthWrite(true);
  68999. engine.setColorWrite(true);
  69000. };
  69001. BoundingBoxRenderer.prototype.dispose = function () {
  69002. if (!this._colorShader) {
  69003. return;
  69004. }
  69005. this.renderList.dispose();
  69006. this._colorShader.dispose();
  69007. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69008. if (buffer) {
  69009. buffer.dispose();
  69010. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69011. }
  69012. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  69013. };
  69014. return BoundingBoxRenderer;
  69015. }());
  69016. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  69017. })(BABYLON || (BABYLON = {}));
  69018. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  69019. var BABYLON;
  69020. (function (BABYLON) {
  69021. var MorphTarget = /** @class */ (function () {
  69022. function MorphTarget(name, influence) {
  69023. if (influence === void 0) { influence = 0; }
  69024. this.name = name;
  69025. this.animations = new Array();
  69026. this._positions = null;
  69027. this._normals = null;
  69028. this._tangents = null;
  69029. this.onInfluenceChanged = new BABYLON.Observable();
  69030. this.influence = influence;
  69031. }
  69032. Object.defineProperty(MorphTarget.prototype, "influence", {
  69033. get: function () {
  69034. return this._influence;
  69035. },
  69036. set: function (influence) {
  69037. if (this._influence === influence) {
  69038. return;
  69039. }
  69040. var previous = this._influence;
  69041. this._influence = influence;
  69042. if (this.onInfluenceChanged.hasObservers) {
  69043. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  69044. }
  69045. },
  69046. enumerable: true,
  69047. configurable: true
  69048. });
  69049. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  69050. get: function () {
  69051. return !!this._positions;
  69052. },
  69053. enumerable: true,
  69054. configurable: true
  69055. });
  69056. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  69057. get: function () {
  69058. return !!this._normals;
  69059. },
  69060. enumerable: true,
  69061. configurable: true
  69062. });
  69063. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  69064. get: function () {
  69065. return !!this._tangents;
  69066. },
  69067. enumerable: true,
  69068. configurable: true
  69069. });
  69070. MorphTarget.prototype.setPositions = function (data) {
  69071. this._positions = data;
  69072. };
  69073. MorphTarget.prototype.getPositions = function () {
  69074. return this._positions;
  69075. };
  69076. MorphTarget.prototype.setNormals = function (data) {
  69077. this._normals = data;
  69078. };
  69079. MorphTarget.prototype.getNormals = function () {
  69080. return this._normals;
  69081. };
  69082. MorphTarget.prototype.setTangents = function (data) {
  69083. this._tangents = data;
  69084. };
  69085. MorphTarget.prototype.getTangents = function () {
  69086. return this._tangents;
  69087. };
  69088. /**
  69089. * Serializes the current target into a Serialization object.
  69090. * Returns the serialized object.
  69091. */
  69092. MorphTarget.prototype.serialize = function () {
  69093. var serializationObject = {};
  69094. serializationObject.name = this.name;
  69095. serializationObject.influence = this.influence;
  69096. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  69097. if (this.hasNormals) {
  69098. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  69099. }
  69100. if (this.hasTangents) {
  69101. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  69102. }
  69103. // Animations
  69104. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  69105. return serializationObject;
  69106. };
  69107. // Statics
  69108. MorphTarget.Parse = function (serializationObject) {
  69109. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  69110. result.setPositions(serializationObject.positions);
  69111. if (serializationObject.normals) {
  69112. result.setNormals(serializationObject.normals);
  69113. }
  69114. if (serializationObject.tangents) {
  69115. result.setTangents(serializationObject.tangents);
  69116. }
  69117. // Animations
  69118. if (serializationObject.animations) {
  69119. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  69120. var parsedAnimation = serializationObject.animations[animationIndex];
  69121. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  69122. }
  69123. }
  69124. return result;
  69125. };
  69126. MorphTarget.FromMesh = function (mesh, name, influence) {
  69127. if (!name) {
  69128. name = mesh.name;
  69129. }
  69130. var result = new MorphTarget(name, influence);
  69131. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  69132. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  69133. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  69134. }
  69135. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  69136. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  69137. }
  69138. return result;
  69139. };
  69140. return MorphTarget;
  69141. }());
  69142. BABYLON.MorphTarget = MorphTarget;
  69143. })(BABYLON || (BABYLON = {}));
  69144. //# sourceMappingURL=babylon.morphTarget.js.map
  69145. var BABYLON;
  69146. (function (BABYLON) {
  69147. var MorphTargetManager = /** @class */ (function () {
  69148. function MorphTargetManager(scene) {
  69149. if (scene === void 0) { scene = null; }
  69150. this._targets = new Array();
  69151. this._targetObservable = new Array();
  69152. this._activeTargets = new BABYLON.SmartArray(16);
  69153. this._supportsNormals = false;
  69154. this._supportsTangents = false;
  69155. this._vertexCount = 0;
  69156. this._uniqueId = 0;
  69157. this._tempInfluences = new Array();
  69158. if (!scene) {
  69159. scene = BABYLON.Engine.LastCreatedScene;
  69160. }
  69161. this._scene = scene;
  69162. if (this._scene) {
  69163. this._scene.morphTargetManagers.push(this);
  69164. this._uniqueId = this._scene.getUniqueId();
  69165. }
  69166. }
  69167. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  69168. get: function () {
  69169. return this._uniqueId;
  69170. },
  69171. enumerable: true,
  69172. configurable: true
  69173. });
  69174. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  69175. get: function () {
  69176. return this._vertexCount;
  69177. },
  69178. enumerable: true,
  69179. configurable: true
  69180. });
  69181. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  69182. get: function () {
  69183. return this._supportsNormals;
  69184. },
  69185. enumerable: true,
  69186. configurable: true
  69187. });
  69188. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  69189. get: function () {
  69190. return this._supportsTangents;
  69191. },
  69192. enumerable: true,
  69193. configurable: true
  69194. });
  69195. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  69196. get: function () {
  69197. return this._targets.length;
  69198. },
  69199. enumerable: true,
  69200. configurable: true
  69201. });
  69202. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  69203. get: function () {
  69204. return this._activeTargets.length;
  69205. },
  69206. enumerable: true,
  69207. configurable: true
  69208. });
  69209. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  69210. get: function () {
  69211. return this._influences;
  69212. },
  69213. enumerable: true,
  69214. configurable: true
  69215. });
  69216. MorphTargetManager.prototype.getActiveTarget = function (index) {
  69217. return this._activeTargets.data[index];
  69218. };
  69219. MorphTargetManager.prototype.getTarget = function (index) {
  69220. return this._targets[index];
  69221. };
  69222. MorphTargetManager.prototype.addTarget = function (target) {
  69223. var _this = this;
  69224. this._targets.push(target);
  69225. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  69226. _this._syncActiveTargets(needUpdate);
  69227. }));
  69228. this._syncActiveTargets(true);
  69229. };
  69230. MorphTargetManager.prototype.removeTarget = function (target) {
  69231. var index = this._targets.indexOf(target);
  69232. if (index >= 0) {
  69233. this._targets.splice(index, 1);
  69234. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  69235. this._syncActiveTargets(true);
  69236. }
  69237. };
  69238. /**
  69239. * Serializes the current manager into a Serialization object.
  69240. * Returns the serialized object.
  69241. */
  69242. MorphTargetManager.prototype.serialize = function () {
  69243. var serializationObject = {};
  69244. serializationObject.id = this.uniqueId;
  69245. serializationObject.targets = [];
  69246. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  69247. var target = _a[_i];
  69248. serializationObject.targets.push(target.serialize());
  69249. }
  69250. return serializationObject;
  69251. };
  69252. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  69253. var influenceCount = 0;
  69254. this._activeTargets.reset();
  69255. this._supportsNormals = true;
  69256. this._supportsTangents = true;
  69257. this._vertexCount = 0;
  69258. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  69259. var target = _a[_i];
  69260. if (target.influence > 0) {
  69261. this._activeTargets.push(target);
  69262. this._tempInfluences[influenceCount++] = target.influence;
  69263. this._supportsNormals = this._supportsNormals && target.hasNormals;
  69264. this._supportsTangents = this._supportsTangents && target.hasTangents;
  69265. var positions = target.getPositions();
  69266. if (!positions) {
  69267. BABYLON.Tools.Error("Invalid target. Target must positions.");
  69268. return;
  69269. }
  69270. var vertexCount = positions.length / 3;
  69271. if (this._vertexCount === 0) {
  69272. this._vertexCount = vertexCount;
  69273. }
  69274. else if (this._vertexCount !== vertexCount) {
  69275. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  69276. return;
  69277. }
  69278. }
  69279. }
  69280. if (!this._influences || this._influences.length !== influenceCount) {
  69281. this._influences = new Float32Array(influenceCount);
  69282. }
  69283. for (var index = 0; index < influenceCount; index++) {
  69284. this._influences[index] = this._tempInfluences[index];
  69285. }
  69286. if (needUpdate && this._scene) {
  69287. // Flag meshes as dirty to resync with the active targets
  69288. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  69289. var mesh = _c[_b];
  69290. if (mesh.morphTargetManager === this) {
  69291. mesh._syncGeometryWithMorphTargetManager();
  69292. }
  69293. }
  69294. }
  69295. };
  69296. // Statics
  69297. MorphTargetManager.Parse = function (serializationObject, scene) {
  69298. var result = new MorphTargetManager(scene);
  69299. result._uniqueId = serializationObject.id;
  69300. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  69301. var targetData = _a[_i];
  69302. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  69303. }
  69304. return result;
  69305. };
  69306. return MorphTargetManager;
  69307. }());
  69308. BABYLON.MorphTargetManager = MorphTargetManager;
  69309. })(BABYLON || (BABYLON = {}));
  69310. //# sourceMappingURL=babylon.morphTargetManager.js.map
  69311. var BABYLON;
  69312. (function (BABYLON) {
  69313. var Octree = /** @class */ (function () {
  69314. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  69315. if (maxDepth === void 0) { maxDepth = 2; }
  69316. this.maxDepth = maxDepth;
  69317. this.dynamicContent = new Array();
  69318. this._maxBlockCapacity = maxBlockCapacity || 64;
  69319. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  69320. this._creationFunc = creationFunc;
  69321. }
  69322. // Methods
  69323. Octree.prototype.update = function (worldMin, worldMax, entries) {
  69324. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  69325. };
  69326. Octree.prototype.addMesh = function (entry) {
  69327. for (var index = 0; index < this.blocks.length; index++) {
  69328. var block = this.blocks[index];
  69329. block.addEntry(entry);
  69330. }
  69331. };
  69332. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  69333. this._selectionContent.reset();
  69334. for (var index = 0; index < this.blocks.length; index++) {
  69335. var block = this.blocks[index];
  69336. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  69337. }
  69338. if (allowDuplicate) {
  69339. this._selectionContent.concat(this.dynamicContent);
  69340. }
  69341. else {
  69342. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  69343. }
  69344. return this._selectionContent;
  69345. };
  69346. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  69347. this._selectionContent.reset();
  69348. for (var index = 0; index < this.blocks.length; index++) {
  69349. var block = this.blocks[index];
  69350. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  69351. }
  69352. if (allowDuplicate) {
  69353. this._selectionContent.concat(this.dynamicContent);
  69354. }
  69355. else {
  69356. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  69357. }
  69358. return this._selectionContent;
  69359. };
  69360. Octree.prototype.intersectsRay = function (ray) {
  69361. this._selectionContent.reset();
  69362. for (var index = 0; index < this.blocks.length; index++) {
  69363. var block = this.blocks[index];
  69364. block.intersectsRay(ray, this._selectionContent);
  69365. }
  69366. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  69367. return this._selectionContent;
  69368. };
  69369. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  69370. target.blocks = new Array();
  69371. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  69372. // Segmenting space
  69373. for (var x = 0; x < 2; x++) {
  69374. for (var y = 0; y < 2; y++) {
  69375. for (var z = 0; z < 2; z++) {
  69376. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  69377. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  69378. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  69379. block.addEntries(entries);
  69380. target.blocks.push(block);
  69381. }
  69382. }
  69383. }
  69384. };
  69385. Octree.CreationFuncForMeshes = function (entry, block) {
  69386. var boundingInfo = entry.getBoundingInfo();
  69387. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  69388. block.entries.push(entry);
  69389. }
  69390. };
  69391. Octree.CreationFuncForSubMeshes = function (entry, block) {
  69392. var boundingInfo = entry.getBoundingInfo();
  69393. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  69394. block.entries.push(entry);
  69395. }
  69396. };
  69397. return Octree;
  69398. }());
  69399. BABYLON.Octree = Octree;
  69400. })(BABYLON || (BABYLON = {}));
  69401. //# sourceMappingURL=babylon.octree.js.map
  69402. var BABYLON;
  69403. (function (BABYLON) {
  69404. var OctreeBlock = /** @class */ (function () {
  69405. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  69406. this.entries = new Array();
  69407. this._boundingVectors = new Array();
  69408. this._capacity = capacity;
  69409. this._depth = depth;
  69410. this._maxDepth = maxDepth;
  69411. this._creationFunc = creationFunc;
  69412. this._minPoint = minPoint;
  69413. this._maxPoint = maxPoint;
  69414. this._boundingVectors.push(minPoint.clone());
  69415. this._boundingVectors.push(maxPoint.clone());
  69416. this._boundingVectors.push(minPoint.clone());
  69417. this._boundingVectors[2].x = maxPoint.x;
  69418. this._boundingVectors.push(minPoint.clone());
  69419. this._boundingVectors[3].y = maxPoint.y;
  69420. this._boundingVectors.push(minPoint.clone());
  69421. this._boundingVectors[4].z = maxPoint.z;
  69422. this._boundingVectors.push(maxPoint.clone());
  69423. this._boundingVectors[5].z = minPoint.z;
  69424. this._boundingVectors.push(maxPoint.clone());
  69425. this._boundingVectors[6].x = minPoint.x;
  69426. this._boundingVectors.push(maxPoint.clone());
  69427. this._boundingVectors[7].y = minPoint.y;
  69428. }
  69429. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  69430. // Property
  69431. get: function () {
  69432. return this._capacity;
  69433. },
  69434. enumerable: true,
  69435. configurable: true
  69436. });
  69437. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  69438. get: function () {
  69439. return this._minPoint;
  69440. },
  69441. enumerable: true,
  69442. configurable: true
  69443. });
  69444. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  69445. get: function () {
  69446. return this._maxPoint;
  69447. },
  69448. enumerable: true,
  69449. configurable: true
  69450. });
  69451. // Methods
  69452. OctreeBlock.prototype.addEntry = function (entry) {
  69453. if (this.blocks) {
  69454. for (var index = 0; index < this.blocks.length; index++) {
  69455. var block = this.blocks[index];
  69456. block.addEntry(entry);
  69457. }
  69458. return;
  69459. }
  69460. this._creationFunc(entry, this);
  69461. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  69462. this.createInnerBlocks();
  69463. }
  69464. };
  69465. OctreeBlock.prototype.addEntries = function (entries) {
  69466. for (var index = 0; index < entries.length; index++) {
  69467. var mesh = entries[index];
  69468. this.addEntry(mesh);
  69469. }
  69470. };
  69471. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  69472. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  69473. if (this.blocks) {
  69474. for (var index = 0; index < this.blocks.length; index++) {
  69475. var block = this.blocks[index];
  69476. block.select(frustumPlanes, selection, allowDuplicate);
  69477. }
  69478. return;
  69479. }
  69480. if (allowDuplicate) {
  69481. selection.concat(this.entries);
  69482. }
  69483. else {
  69484. selection.concatWithNoDuplicate(this.entries);
  69485. }
  69486. }
  69487. };
  69488. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  69489. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  69490. if (this.blocks) {
  69491. for (var index = 0; index < this.blocks.length; index++) {
  69492. var block = this.blocks[index];
  69493. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  69494. }
  69495. return;
  69496. }
  69497. if (allowDuplicate) {
  69498. selection.concat(this.entries);
  69499. }
  69500. else {
  69501. selection.concatWithNoDuplicate(this.entries);
  69502. }
  69503. }
  69504. };
  69505. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  69506. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  69507. if (this.blocks) {
  69508. for (var index = 0; index < this.blocks.length; index++) {
  69509. var block = this.blocks[index];
  69510. block.intersectsRay(ray, selection);
  69511. }
  69512. return;
  69513. }
  69514. selection.concatWithNoDuplicate(this.entries);
  69515. }
  69516. };
  69517. OctreeBlock.prototype.createInnerBlocks = function () {
  69518. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  69519. };
  69520. return OctreeBlock;
  69521. }());
  69522. BABYLON.OctreeBlock = OctreeBlock;
  69523. })(BABYLON || (BABYLON = {}));
  69524. //# sourceMappingURL=babylon.octreeBlock.js.map
  69525. var BABYLON;
  69526. (function (BABYLON) {
  69527. var SIMDVector3 = /** @class */ (function () {
  69528. function SIMDVector3() {
  69529. }
  69530. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  69531. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  69532. };
  69533. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  69534. var m = transformation.m;
  69535. var m0 = SIMD.Float32x4.load(m, 0);
  69536. var m1 = SIMD.Float32x4.load(m, 4);
  69537. var m2 = SIMD.Float32x4.load(m, 8);
  69538. var m3 = SIMD.Float32x4.load(m, 12);
  69539. var r = SIMD.Float32x4.add(SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(x), m0), SIMD.Float32x4.mul(SIMD.Float32x4.splat(y), m1)), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(z), m2), m3));
  69540. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  69541. result.x = SIMD.Float32x4.extractLane(r, 0);
  69542. result.y = SIMD.Float32x4.extractLane(r, 1);
  69543. result.z = SIMD.Float32x4.extractLane(r, 2);
  69544. };
  69545. return SIMDVector3;
  69546. }());
  69547. var SIMDMatrix = /** @class */ (function () {
  69548. function SIMDMatrix() {
  69549. }
  69550. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  69551. var tm = this.m;
  69552. var om = other.m;
  69553. var m0 = SIMD.Float32x4.load(om, 0);
  69554. var m1 = SIMD.Float32x4.load(om, 4);
  69555. var m2 = SIMD.Float32x4.load(om, 8);
  69556. var m3 = SIMD.Float32x4.load(om, 12);
  69557. for (var i = 0; i < 16; i += 4) {
  69558. SIMD.Float32x4.store(result, i + offset, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i]), m0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 1]), m1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 2]), m2), SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 3]), m3)))));
  69559. }
  69560. return this;
  69561. };
  69562. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  69563. var src = this.m;
  69564. var dest = other.m;
  69565. // Load the 4 rows
  69566. var src0 = SIMD.Float32x4.load(src, 0);
  69567. var src1 = SIMD.Float32x4.load(src, 4);
  69568. var src2 = SIMD.Float32x4.load(src, 8);
  69569. var src3 = SIMD.Float32x4.load(src, 12);
  69570. // Transpose the source matrix. Sort of. Not a true transpose operation
  69571. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  69572. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  69573. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  69574. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  69575. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  69576. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  69577. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  69578. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  69579. // This is a true transposition, but it will lead to an incorrect result
  69580. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  69581. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  69582. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  69583. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  69584. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  69585. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  69586. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  69587. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  69588. // ----
  69589. tmp1 = SIMD.Float32x4.mul(row2, row3);
  69590. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69591. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  69592. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  69593. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69594. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  69595. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  69596. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  69597. // ----
  69598. tmp1 = SIMD.Float32x4.mul(row1, row2);
  69599. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69600. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  69601. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  69602. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69603. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  69604. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  69605. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  69606. // ----
  69607. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  69608. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69609. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  69610. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  69611. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  69612. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69613. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  69614. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  69615. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  69616. // ----
  69617. tmp1 = SIMD.Float32x4.mul(row0, row1);
  69618. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69619. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  69620. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  69621. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69622. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  69623. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  69624. // ----
  69625. tmp1 = SIMD.Float32x4.mul(row0, row3);
  69626. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69627. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  69628. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  69629. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69630. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  69631. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  69632. // ----
  69633. tmp1 = SIMD.Float32x4.mul(row0, row2);
  69634. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69635. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  69636. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  69637. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69638. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  69639. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  69640. // Compute determinant
  69641. var det = SIMD.Float32x4.mul(row0, minor0);
  69642. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  69643. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  69644. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  69645. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  69646. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  69647. // These shuffles aren't necessary if the faulty transposition is done
  69648. // up at the top of this function.
  69649. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  69650. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  69651. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  69652. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  69653. // Compute final values by multiplying with 1/det
  69654. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  69655. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  69656. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  69657. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  69658. return this;
  69659. };
  69660. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  69661. var out = result.m;
  69662. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  69663. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  69664. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  69665. // cc.kmVec3Subtract(f, pCenter, pEye);
  69666. var f = SIMD.Float32x4.sub(center, eye);
  69667. // cc.kmVec3Normalize(f, f);
  69668. var tmp = SIMD.Float32x4.mul(f, f);
  69669. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  69670. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  69671. // cc.kmVec3Assign(up, pUp);
  69672. // cc.kmVec3Normalize(up, up);
  69673. tmp = SIMD.Float32x4.mul(up, up);
  69674. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  69675. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  69676. // cc.kmVec3Cross(s, f, up);
  69677. var s = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 1, 2, 0, 3), SIMD.Float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 2, 0, 1, 3), SIMD.Float32x4.swizzle(up, 1, 2, 0, 3)));
  69678. // cc.kmVec3Normalize(s, s);
  69679. tmp = SIMD.Float32x4.mul(s, s);
  69680. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  69681. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  69682. // cc.kmVec3Cross(u, s, f);
  69683. var u = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 1, 2, 0, 3), SIMD.Float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 2, 0, 1, 3), SIMD.Float32x4.swizzle(f, 1, 2, 0, 3)));
  69684. // cc.kmVec3Normalize(s, s);
  69685. tmp = SIMD.Float32x4.mul(s, s);
  69686. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  69687. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  69688. var zero = SIMD.Float32x4.splat(0.0);
  69689. s = SIMD.Float32x4.neg(s);
  69690. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  69691. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  69692. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  69693. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  69694. var a2 = SIMD.Float32x4.shuffle(SIMD.Float32x4.shuffle(s, u, 2, 3, 6, 7), SIMD.Float32x4.shuffle(f, zero, 2, 3, 6, 7), 0, 2, 4, 6);
  69695. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  69696. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  69697. SIMD.Float32x4.store(out, 0, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  69698. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  69699. SIMD.Float32x4.store(out, 4, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  69700. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  69701. SIMD.Float32x4.store(out, 8, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  69702. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  69703. SIMD.Float32x4.store(out, 12, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  69704. };
  69705. return SIMDMatrix;
  69706. }());
  69707. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  69708. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  69709. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  69710. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  69711. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  69712. var SIMDHelper = /** @class */ (function () {
  69713. function SIMDHelper() {
  69714. }
  69715. Object.defineProperty(SIMDHelper, "IsEnabled", {
  69716. get: function () {
  69717. return SIMDHelper._isEnabled;
  69718. },
  69719. enumerable: true,
  69720. configurable: true
  69721. });
  69722. SIMDHelper.DisableSIMD = function () {
  69723. // Replace functions
  69724. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  69725. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  69726. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  69727. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  69728. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  69729. SIMDHelper._isEnabled = false;
  69730. };
  69731. SIMDHelper.EnableSIMD = function () {
  69732. if (self.SIMD === undefined) {
  69733. return;
  69734. }
  69735. // check if polyfills needed
  69736. if (!self.Math.fround) {
  69737. self.Math.fround = (function (array) { return function (x) {
  69738. return array[0] = x, array[0];
  69739. }; })(new Float32Array(1));
  69740. }
  69741. if (!self.Math.imul) {
  69742. self.Math.imul = function (a, b) {
  69743. var ah = (a >>> 16) & 0xffff;
  69744. var al = a & 0xffff;
  69745. var bh = (b >>> 16) & 0xffff;
  69746. var bl = b & 0xffff;
  69747. // the shift by 0 fixes the sign on the high part
  69748. // the final |0 converts the unsigned value into a signed value
  69749. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  69750. };
  69751. }
  69752. // Replace functions
  69753. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  69754. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  69755. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  69756. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  69757. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  69758. SIMDHelper._isEnabled = true;
  69759. };
  69760. SIMDHelper._isEnabled = false;
  69761. return SIMDHelper;
  69762. }());
  69763. BABYLON.SIMDHelper = SIMDHelper;
  69764. })(BABYLON || (BABYLON = {}));
  69765. //# sourceMappingURL=babylon.math.SIMD.js.map
  69766. var BABYLON;
  69767. (function (BABYLON) {
  69768. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  69769. __extends(VRDistortionCorrectionPostProcess, _super);
  69770. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  69771. var _this = _super.call(this, name, "vrDistortionCorrection", [
  69772. 'LensCenter',
  69773. 'Scale',
  69774. 'ScaleIn',
  69775. 'HmdWarpParam'
  69776. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  69777. _this._isRightEye = isRightEye;
  69778. _this._distortionFactors = vrMetrics.distortionK;
  69779. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  69780. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  69781. _this.adaptScaleToCurrentViewport = true;
  69782. _this.onSizeChangedObservable.add(function () {
  69783. _this.aspectRatio = _this.width * .5 / _this.height;
  69784. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  69785. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  69786. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  69787. });
  69788. _this.onApplyObservable.add(function (effect) {
  69789. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  69790. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  69791. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  69792. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  69793. });
  69794. return _this;
  69795. }
  69796. return VRDistortionCorrectionPostProcess;
  69797. }(BABYLON.PostProcess));
  69798. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  69799. })(BABYLON || (BABYLON = {}));
  69800. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  69801. var BABYLON;
  69802. (function (BABYLON) {
  69803. var AnaglyphPostProcess = /** @class */ (function (_super) {
  69804. __extends(AnaglyphPostProcess, _super);
  69805. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  69806. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  69807. _this._passedProcess = rigCameras[0]._rigPostProcess;
  69808. _this.onApplyObservable.add(function (effect) {
  69809. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  69810. });
  69811. return _this;
  69812. }
  69813. return AnaglyphPostProcess;
  69814. }(BABYLON.PostProcess));
  69815. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  69816. })(BABYLON || (BABYLON = {}));
  69817. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  69818. var BABYLON;
  69819. (function (BABYLON) {
  69820. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  69821. __extends(StereoscopicInterlacePostProcess, _super);
  69822. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  69823. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  69824. _this._passedProcess = rigCameras[0]._rigPostProcess;
  69825. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  69826. _this.onSizeChangedObservable.add(function () {
  69827. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  69828. });
  69829. _this.onApplyObservable.add(function (effect) {
  69830. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  69831. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  69832. });
  69833. return _this;
  69834. }
  69835. return StereoscopicInterlacePostProcess;
  69836. }(BABYLON.PostProcess));
  69837. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  69838. })(BABYLON || (BABYLON = {}));
  69839. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  69840. var BABYLON;
  69841. (function (BABYLON) {
  69842. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  69843. function FreeCameraDeviceOrientationInput() {
  69844. var _this = this;
  69845. this._screenOrientationAngle = 0;
  69846. this._screenQuaternion = new BABYLON.Quaternion();
  69847. this._alpha = 0;
  69848. this._beta = 0;
  69849. this._gamma = 0;
  69850. this._orientationChanged = function () {
  69851. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  69852. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  69853. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  69854. };
  69855. this._deviceOrientation = function (evt) {
  69856. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  69857. _this._beta = evt.beta !== null ? evt.beta : 0;
  69858. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  69859. };
  69860. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  69861. this._orientationChanged();
  69862. }
  69863. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  69864. get: function () {
  69865. return this._camera;
  69866. },
  69867. set: function (camera) {
  69868. this._camera = camera;
  69869. if (this._camera != null && !this._camera.rotationQuaternion) {
  69870. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  69871. }
  69872. },
  69873. enumerable: true,
  69874. configurable: true
  69875. });
  69876. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  69877. window.addEventListener("orientationchange", this._orientationChanged);
  69878. window.addEventListener("deviceorientation", this._deviceOrientation);
  69879. //In certain cases, the attach control is called AFTER orientation was changed,
  69880. //So this is needed.
  69881. this._orientationChanged();
  69882. };
  69883. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  69884. window.removeEventListener("orientationchange", this._orientationChanged);
  69885. window.removeEventListener("deviceorientation", this._deviceOrientation);
  69886. };
  69887. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  69888. //if no device orientation provided, don't update the rotation.
  69889. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  69890. if (!this._alpha)
  69891. return;
  69892. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  69893. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  69894. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  69895. //Mirror on XY Plane
  69896. this._camera.rotationQuaternion.z *= -1;
  69897. this._camera.rotationQuaternion.w *= -1;
  69898. };
  69899. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  69900. return "FreeCameraDeviceOrientationInput";
  69901. };
  69902. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  69903. return "deviceOrientation";
  69904. };
  69905. return FreeCameraDeviceOrientationInput;
  69906. }());
  69907. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  69908. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  69909. })(BABYLON || (BABYLON = {}));
  69910. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  69911. var BABYLON;
  69912. (function (BABYLON) {
  69913. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  69914. function ArcRotateCameraVRDeviceOrientationInput() {
  69915. this.alphaCorrection = 1;
  69916. this.betaCorrection = 1;
  69917. this.gammaCorrection = 1;
  69918. this._alpha = 0;
  69919. this._gamma = 0;
  69920. this._dirty = false;
  69921. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  69922. }
  69923. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  69924. this.camera.attachControl(element, noPreventDefault);
  69925. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  69926. };
  69927. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  69928. if (evt.alpha !== null) {
  69929. this._alpha = +evt.alpha | 0;
  69930. }
  69931. if (evt.gamma !== null) {
  69932. this._gamma = +evt.gamma | 0;
  69933. }
  69934. this._dirty = true;
  69935. };
  69936. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  69937. if (this._dirty) {
  69938. this._dirty = false;
  69939. if (this._gamma < 0) {
  69940. this._gamma = 180 + this._gamma;
  69941. }
  69942. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  69943. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  69944. }
  69945. };
  69946. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  69947. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  69948. };
  69949. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  69950. return "ArcRotateCameraVRDeviceOrientationInput";
  69951. };
  69952. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  69953. return "VRDeviceOrientation";
  69954. };
  69955. return ArcRotateCameraVRDeviceOrientationInput;
  69956. }());
  69957. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  69958. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  69959. })(BABYLON || (BABYLON = {}));
  69960. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  69961. var BABYLON;
  69962. (function (BABYLON) {
  69963. var VRCameraMetrics = /** @class */ (function () {
  69964. function VRCameraMetrics() {
  69965. this.compensateDistortion = true;
  69966. }
  69967. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  69968. get: function () {
  69969. return this.hResolution / (2 * this.vResolution);
  69970. },
  69971. enumerable: true,
  69972. configurable: true
  69973. });
  69974. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  69975. get: function () {
  69976. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  69977. },
  69978. enumerable: true,
  69979. configurable: true
  69980. });
  69981. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  69982. get: function () {
  69983. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  69984. var h = (4 * meters) / this.hScreenSize;
  69985. return BABYLON.Matrix.Translation(h, 0, 0);
  69986. },
  69987. enumerable: true,
  69988. configurable: true
  69989. });
  69990. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  69991. get: function () {
  69992. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  69993. var h = (4 * meters) / this.hScreenSize;
  69994. return BABYLON.Matrix.Translation(-h, 0, 0);
  69995. },
  69996. enumerable: true,
  69997. configurable: true
  69998. });
  69999. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  70000. get: function () {
  70001. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  70002. },
  70003. enumerable: true,
  70004. configurable: true
  70005. });
  70006. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  70007. get: function () {
  70008. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  70009. },
  70010. enumerable: true,
  70011. configurable: true
  70012. });
  70013. VRCameraMetrics.GetDefault = function () {
  70014. var result = new VRCameraMetrics();
  70015. result.hResolution = 1280;
  70016. result.vResolution = 800;
  70017. result.hScreenSize = 0.149759993;
  70018. result.vScreenSize = 0.0935999975;
  70019. result.vScreenCenter = 0.0467999987;
  70020. result.eyeToScreenDistance = 0.0410000011;
  70021. result.lensSeparationDistance = 0.0635000020;
  70022. result.interpupillaryDistance = 0.0640000030;
  70023. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  70024. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  70025. result.postProcessScaleFactor = 1.714605507808412;
  70026. result.lensCenterOffset = 0.151976421;
  70027. return result;
  70028. };
  70029. return VRCameraMetrics;
  70030. }());
  70031. BABYLON.VRCameraMetrics = VRCameraMetrics;
  70032. })(BABYLON || (BABYLON = {}));
  70033. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  70034. var BABYLON;
  70035. (function (BABYLON) {
  70036. var WebVRFreeCamera = /** @class */ (function (_super) {
  70037. __extends(WebVRFreeCamera, _super);
  70038. function WebVRFreeCamera(name, position, scene, webVROptions) {
  70039. if (webVROptions === void 0) { webVROptions = {}; }
  70040. var _this = _super.call(this, name, position, scene) || this;
  70041. _this.webVROptions = webVROptions;
  70042. _this._vrDevice = null;
  70043. _this.rawPose = null;
  70044. _this._specsVersion = "1.1";
  70045. _this._attached = false;
  70046. _this._descendants = [];
  70047. _this.devicePosition = BABYLON.Vector3.Zero();
  70048. _this.deviceScaleFactor = 1;
  70049. _this.controllers = [];
  70050. _this.onControllersAttachedObservable = new BABYLON.Observable();
  70051. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  70052. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  70053. _this.minZ = 0.1;
  70054. //legacy support - the compensation boolean was removed.
  70055. if (arguments.length === 5) {
  70056. _this.webVROptions = arguments[4];
  70057. }
  70058. // default webVR options
  70059. if (_this.webVROptions.trackPosition == undefined) {
  70060. _this.webVROptions.trackPosition = true;
  70061. }
  70062. if (_this.webVROptions.controllerMeshes == undefined) {
  70063. _this.webVROptions.controllerMeshes = true;
  70064. }
  70065. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  70066. _this.webVROptions.defaultLightingOnControllers = true;
  70067. }
  70068. _this.rotationQuaternion = new BABYLON.Quaternion();
  70069. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  70070. if (_this.webVROptions && _this.webVROptions.positionScale) {
  70071. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  70072. }
  70073. //enable VR
  70074. var engine = _this.getEngine();
  70075. _this._onVREnabled = function (success) { if (success) {
  70076. _this.initControllers();
  70077. } };
  70078. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  70079. engine.initWebVR().add(function (event) {
  70080. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  70081. return;
  70082. }
  70083. _this._vrDevice = event.vrDisplay;
  70084. //reset the rig parameters.
  70085. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  70086. if (_this._attached) {
  70087. _this.getEngine().enableVR();
  70088. }
  70089. });
  70090. if (typeof (VRFrameData) !== "undefined")
  70091. _this._frameData = new VRFrameData();
  70092. /**
  70093. * The idea behind the following lines:
  70094. * objects that have the camera as parent should actually have the rig cameras as a parent.
  70095. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  70096. * the second will not show it correctly.
  70097. *
  70098. * To solve this - each object that has the camera as parent will be added to a protected array.
  70099. * When the rig camera renders, it will take this array and set all of those to be its children.
  70100. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  70101. * Amazing!
  70102. */
  70103. scene.onBeforeCameraRenderObservable.add(function (camera) {
  70104. if (camera.parent === _this && _this.rigParenting) {
  70105. _this._descendants = _this.getDescendants(true, function (n) {
  70106. // don't take the cameras or the controllers!
  70107. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  70108. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  70109. return !isController && !isRigCamera;
  70110. });
  70111. _this._descendants.forEach(function (node) {
  70112. node.parent = camera;
  70113. });
  70114. }
  70115. });
  70116. scene.onAfterCameraRenderObservable.add(function (camera) {
  70117. if (camera.parent === _this && _this.rigParenting) {
  70118. _this._descendants.forEach(function (node) {
  70119. node.parent = _this;
  70120. });
  70121. }
  70122. });
  70123. return _this;
  70124. }
  70125. WebVRFreeCamera.prototype.dispose = function () {
  70126. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  70127. _super.prototype.dispose.call(this);
  70128. };
  70129. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  70130. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  70131. var gp = _a[_i];
  70132. if (gp.hand === name) {
  70133. return gp;
  70134. }
  70135. }
  70136. return null;
  70137. };
  70138. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  70139. get: function () {
  70140. if (!this._leftController) {
  70141. this._leftController = this.getControllerByName("left");
  70142. }
  70143. return this._leftController;
  70144. },
  70145. enumerable: true,
  70146. configurable: true
  70147. });
  70148. ;
  70149. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  70150. get: function () {
  70151. if (!this._rightController) {
  70152. this._rightController = this.getControllerByName("right");
  70153. }
  70154. return this._rightController;
  70155. },
  70156. enumerable: true,
  70157. configurable: true
  70158. });
  70159. ;
  70160. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  70161. if (length === void 0) { length = 100; }
  70162. if (this.leftCamera) {
  70163. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  70164. }
  70165. else {
  70166. return _super.prototype.getForwardRay.call(this, length);
  70167. }
  70168. };
  70169. WebVRFreeCamera.prototype._checkInputs = function () {
  70170. if (this._vrDevice && this._vrDevice.isPresenting) {
  70171. this._vrDevice.getFrameData(this._frameData);
  70172. this.updateFromDevice(this._frameData.pose);
  70173. }
  70174. _super.prototype._checkInputs.call(this);
  70175. };
  70176. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  70177. if (poseData && poseData.orientation) {
  70178. this.rawPose = poseData;
  70179. this.deviceRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  70180. if (this.getScene().useRightHandedSystem) {
  70181. this.deviceRotationQuaternion.z *= -1;
  70182. this.deviceRotationQuaternion.w *= -1;
  70183. }
  70184. if (this.webVROptions.trackPosition && this.rawPose.position) {
  70185. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  70186. if (this.getScene().useRightHandedSystem) {
  70187. this.devicePosition.z *= -1;
  70188. }
  70189. }
  70190. }
  70191. };
  70192. /**
  70193. * WebVR's attach control will start broadcasting frames to the device.
  70194. * Note that in certain browsers (chrome for example) this function must be called
  70195. * within a user-interaction callback. Example:
  70196. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  70197. *
  70198. * @param {HTMLElement} element
  70199. * @param {boolean} [noPreventDefault]
  70200. *
  70201. * @memberOf WebVRFreeCamera
  70202. */
  70203. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  70204. _super.prototype.attachControl.call(this, element, noPreventDefault);
  70205. this._attached = true;
  70206. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  70207. if (this._vrDevice) {
  70208. this.getEngine().enableVR();
  70209. }
  70210. };
  70211. WebVRFreeCamera.prototype.detachControl = function (element) {
  70212. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70213. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70214. _super.prototype.detachControl.call(this, element);
  70215. this._attached = false;
  70216. this.getEngine().disableVR();
  70217. };
  70218. WebVRFreeCamera.prototype.getClassName = function () {
  70219. return "WebVRFreeCamera";
  70220. };
  70221. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  70222. //uses the vrDisplay's "resetPose()".
  70223. //pitch and roll won't be affected.
  70224. this._vrDevice.resetPose();
  70225. };
  70226. WebVRFreeCamera.prototype._updateRigCameras = function () {
  70227. var camLeft = this._rigCameras[0];
  70228. var camRight = this._rigCameras[1];
  70229. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  70230. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  70231. camLeft.position.copyFrom(this.devicePosition);
  70232. camRight.position.copyFrom(this.devicePosition);
  70233. };
  70234. /**
  70235. * This function is called by the two RIG cameras.
  70236. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  70237. */
  70238. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  70239. var _this = this;
  70240. //WebVR 1.1
  70241. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  70242. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  70243. if (!this.getScene().useRightHandedSystem) {
  70244. [2, 6, 8, 9, 14].forEach(function (num) {
  70245. _this._webvrViewMatrix.m[num] *= -1;
  70246. });
  70247. }
  70248. // update the camera rotation matrix
  70249. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  70250. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  70251. // Computing target and final matrix
  70252. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  70253. var parentCamera = this._cameraRigParams["parentCamera"];
  70254. // should the view matrix be updated with scale and position offset?
  70255. if (parentCamera.deviceScaleFactor !== 1) {
  70256. this._webvrViewMatrix.invert();
  70257. // scale the position, if set
  70258. if (parentCamera.deviceScaleFactor) {
  70259. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  70260. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  70261. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  70262. }
  70263. this._webvrViewMatrix.invert();
  70264. }
  70265. return this._webvrViewMatrix;
  70266. };
  70267. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  70268. var _this = this;
  70269. var parentCamera = this.parent;
  70270. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  70271. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  70272. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  70273. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  70274. //babylon compatible matrix
  70275. if (!this.getScene().useRightHandedSystem) {
  70276. [8, 9, 10, 11].forEach(function (num) {
  70277. _this._projectionMatrix.m[num] *= -1;
  70278. });
  70279. }
  70280. return this._projectionMatrix;
  70281. };
  70282. WebVRFreeCamera.prototype.initControllers = function () {
  70283. var _this = this;
  70284. this.controllers = [];
  70285. var manager = this.getScene().gamepadManager;
  70286. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70287. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  70288. var webVrController = gamepad;
  70289. if (webVrController.defaultModel) {
  70290. webVrController.defaultModel.setEnabled(false);
  70291. }
  70292. }
  70293. });
  70294. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70295. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  70296. var webVrController_1 = gamepad;
  70297. if (_this.webVROptions.controllerMeshes) {
  70298. if (webVrController_1.defaultModel) {
  70299. webVrController_1.defaultModel.setEnabled(true);
  70300. }
  70301. else {
  70302. // Load the meshes
  70303. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  70304. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  70305. if (_this.webVROptions.defaultLightingOnControllers) {
  70306. if (!_this._lightOnControllers) {
  70307. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  70308. }
  70309. var activateLightOnSubMeshes_1 = function (mesh, light) {
  70310. var children = mesh.getChildren();
  70311. if (children.length !== 0) {
  70312. children.forEach(function (mesh) {
  70313. light.includedOnlyMeshes.push(mesh);
  70314. activateLightOnSubMeshes_1(mesh, light);
  70315. });
  70316. }
  70317. };
  70318. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  70319. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  70320. }
  70321. });
  70322. }
  70323. }
  70324. webVrController_1.attachToPoseControlledCamera(_this);
  70325. // since this is async - sanity check. Is the controller already stored?
  70326. if (_this.controllers.indexOf(webVrController_1) === -1) {
  70327. //add to the controllers array
  70328. _this.controllers.push(webVrController_1);
  70329. //did we find enough controllers? Great! let the developer know.
  70330. if (_this.controllers.length >= 2) {
  70331. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  70332. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  70333. // So we're overriding setting left & right manually to be sure
  70334. var firstViveWandDetected = false;
  70335. for (var i = 0; i < _this.controllers.length; i++) {
  70336. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  70337. if (!firstViveWandDetected) {
  70338. firstViveWandDetected = true;
  70339. _this.controllers[i].hand = "left";
  70340. }
  70341. else {
  70342. _this.controllers[i].hand = "right";
  70343. }
  70344. }
  70345. }
  70346. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  70347. }
  70348. }
  70349. }
  70350. });
  70351. };
  70352. return WebVRFreeCamera;
  70353. }(BABYLON.FreeCamera));
  70354. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  70355. })(BABYLON || (BABYLON = {}));
  70356. //# sourceMappingURL=babylon.webVRCamera.js.map
  70357. var BABYLON;
  70358. (function (BABYLON) {
  70359. // We're mainly based on the logic defined into the FreeCamera code
  70360. var DeviceOrientationCamera = /** @class */ (function (_super) {
  70361. __extends(DeviceOrientationCamera, _super);
  70362. function DeviceOrientationCamera(name, position, scene) {
  70363. var _this = _super.call(this, name, position, scene) || this;
  70364. _this._quaternionCache = new BABYLON.Quaternion();
  70365. _this.inputs.addDeviceOrientation();
  70366. return _this;
  70367. }
  70368. DeviceOrientationCamera.prototype.getClassName = function () {
  70369. return "DeviceOrientationCamera";
  70370. };
  70371. DeviceOrientationCamera.prototype._checkInputs = function () {
  70372. _super.prototype._checkInputs.call(this);
  70373. this._quaternionCache.copyFrom(this.rotationQuaternion);
  70374. if (this._initialQuaternion) {
  70375. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  70376. }
  70377. };
  70378. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  70379. var _this = this;
  70380. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  70381. //can only work if this camera has a rotation quaternion already.
  70382. if (!this.rotationQuaternion)
  70383. return;
  70384. if (!this._initialQuaternion) {
  70385. this._initialQuaternion = new BABYLON.Quaternion();
  70386. }
  70387. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  70388. ['x', 'y', 'z'].forEach(function (axisName) {
  70389. if (!axis[axisName]) {
  70390. _this._initialQuaternion[axisName] = 0;
  70391. }
  70392. else {
  70393. _this._initialQuaternion[axisName] *= -1;
  70394. }
  70395. });
  70396. this._initialQuaternion.normalize();
  70397. //force rotation update
  70398. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  70399. };
  70400. return DeviceOrientationCamera;
  70401. }(BABYLON.FreeCamera));
  70402. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  70403. })(BABYLON || (BABYLON = {}));
  70404. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  70405. var BABYLON;
  70406. (function (BABYLON) {
  70407. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  70408. __extends(VRDeviceOrientationFreeCamera, _super);
  70409. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  70410. if (compensateDistortion === void 0) { compensateDistortion = true; }
  70411. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  70412. var _this = _super.call(this, name, position, scene) || this;
  70413. vrCameraMetrics.compensateDistortion = compensateDistortion;
  70414. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  70415. return _this;
  70416. }
  70417. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  70418. return "VRDeviceOrientationFreeCamera";
  70419. };
  70420. return VRDeviceOrientationFreeCamera;
  70421. }(BABYLON.DeviceOrientationCamera));
  70422. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  70423. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  70424. __extends(VRDeviceOrientationGamepadCamera, _super);
  70425. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  70426. if (compensateDistortion === void 0) { compensateDistortion = true; }
  70427. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  70428. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  70429. _this.inputs.addGamepad();
  70430. return _this;
  70431. }
  70432. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  70433. return "VRDeviceOrientationGamepadCamera";
  70434. };
  70435. return VRDeviceOrientationGamepadCamera;
  70436. }(VRDeviceOrientationFreeCamera));
  70437. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  70438. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  70439. __extends(VRDeviceOrientationArcRotateCamera, _super);
  70440. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  70441. if (compensateDistortion === void 0) { compensateDistortion = true; }
  70442. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  70443. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  70444. vrCameraMetrics.compensateDistortion = compensateDistortion;
  70445. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  70446. _this.inputs.addVRDeviceOrientation();
  70447. return _this;
  70448. }
  70449. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  70450. return "VRDeviceOrientationArcRotateCamera";
  70451. };
  70452. return VRDeviceOrientationArcRotateCamera;
  70453. }(BABYLON.ArcRotateCamera));
  70454. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  70455. })(BABYLON || (BABYLON = {}));
  70456. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  70457. var BABYLON;
  70458. (function (BABYLON) {
  70459. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  70460. __extends(AnaglyphFreeCamera, _super);
  70461. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  70462. var _this = _super.call(this, name, position, scene) || this;
  70463. _this.interaxialDistance = interaxialDistance;
  70464. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  70465. return _this;
  70466. }
  70467. AnaglyphFreeCamera.prototype.getClassName = function () {
  70468. return "AnaglyphFreeCamera";
  70469. };
  70470. return AnaglyphFreeCamera;
  70471. }(BABYLON.FreeCamera));
  70472. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  70473. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  70474. __extends(AnaglyphArcRotateCamera, _super);
  70475. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  70476. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  70477. _this.interaxialDistance = interaxialDistance;
  70478. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  70479. return _this;
  70480. }
  70481. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  70482. return "AnaglyphArcRotateCamera";
  70483. };
  70484. return AnaglyphArcRotateCamera;
  70485. }(BABYLON.ArcRotateCamera));
  70486. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  70487. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  70488. __extends(AnaglyphGamepadCamera, _super);
  70489. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  70490. var _this = _super.call(this, name, position, scene) || this;
  70491. _this.interaxialDistance = interaxialDistance;
  70492. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  70493. return _this;
  70494. }
  70495. AnaglyphGamepadCamera.prototype.getClassName = function () {
  70496. return "AnaglyphGamepadCamera";
  70497. };
  70498. return AnaglyphGamepadCamera;
  70499. }(BABYLON.GamepadCamera));
  70500. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  70501. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  70502. __extends(AnaglyphUniversalCamera, _super);
  70503. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  70504. var _this = _super.call(this, name, position, scene) || this;
  70505. _this.interaxialDistance = interaxialDistance;
  70506. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  70507. return _this;
  70508. }
  70509. AnaglyphUniversalCamera.prototype.getClassName = function () {
  70510. return "AnaglyphUniversalCamera";
  70511. };
  70512. return AnaglyphUniversalCamera;
  70513. }(BABYLON.UniversalCamera));
  70514. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  70515. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  70516. __extends(StereoscopicFreeCamera, _super);
  70517. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  70518. var _this = _super.call(this, name, position, scene) || this;
  70519. _this.interaxialDistance = interaxialDistance;
  70520. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  70521. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  70522. return _this;
  70523. }
  70524. StereoscopicFreeCamera.prototype.getClassName = function () {
  70525. return "StereoscopicFreeCamera";
  70526. };
  70527. return StereoscopicFreeCamera;
  70528. }(BABYLON.FreeCamera));
  70529. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  70530. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  70531. __extends(StereoscopicArcRotateCamera, _super);
  70532. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  70533. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  70534. _this.interaxialDistance = interaxialDistance;
  70535. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  70536. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  70537. return _this;
  70538. }
  70539. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  70540. return "StereoscopicArcRotateCamera";
  70541. };
  70542. return StereoscopicArcRotateCamera;
  70543. }(BABYLON.ArcRotateCamera));
  70544. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  70545. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  70546. __extends(StereoscopicGamepadCamera, _super);
  70547. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  70548. var _this = _super.call(this, name, position, scene) || this;
  70549. _this.interaxialDistance = interaxialDistance;
  70550. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  70551. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  70552. return _this;
  70553. }
  70554. StereoscopicGamepadCamera.prototype.getClassName = function () {
  70555. return "StereoscopicGamepadCamera";
  70556. };
  70557. return StereoscopicGamepadCamera;
  70558. }(BABYLON.GamepadCamera));
  70559. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  70560. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  70561. __extends(StereoscopicUniversalCamera, _super);
  70562. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  70563. var _this = _super.call(this, name, position, scene) || this;
  70564. _this.interaxialDistance = interaxialDistance;
  70565. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  70566. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  70567. return _this;
  70568. }
  70569. StereoscopicUniversalCamera.prototype.getClassName = function () {
  70570. return "StereoscopicUniversalCamera";
  70571. };
  70572. return StereoscopicUniversalCamera;
  70573. }(BABYLON.UniversalCamera));
  70574. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  70575. })(BABYLON || (BABYLON = {}));
  70576. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  70577. var BABYLON;
  70578. (function (BABYLON) {
  70579. var VRExperienceHelper = /** @class */ (function () {
  70580. function VRExperienceHelper(scene, webVROptions) {
  70581. if (webVROptions === void 0) { webVROptions = {}; }
  70582. var _this = this;
  70583. this.webVROptions = webVROptions;
  70584. // Can the system support WebVR, even if a headset isn't plugged in?
  70585. this._webVRsupported = false;
  70586. // If WebVR is supported, is a headset plugged in and are we ready to present?
  70587. this._webVRready = false;
  70588. // Are we waiting for the requestPresent callback to complete?
  70589. this._webVRrequesting = false;
  70590. // Are we presenting to the headset right now?
  70591. this._webVRpresenting = false;
  70592. // Are we presenting in the fullscreen fallback?
  70593. this._fullscreenVRpresenting = false;
  70594. this._useCustomVRButton = false;
  70595. this._teleportationRequested = false;
  70596. this._teleportationEnabledOnLeftController = false;
  70597. this._teleportationEnabledOnRightController = false;
  70598. this._leftControllerReady = false;
  70599. this._rightControllerReady = false;
  70600. this._teleportationAllowed = false;
  70601. this._rotationAllowed = true;
  70602. this._teleportationRequestInitiated = false;
  70603. this._xboxGamepadTeleportationRequestInitiated = false;
  70604. this._rotationRightAsked = false;
  70605. this._rotationLeftAsked = false;
  70606. this._teleportationFillColor = "#444444";
  70607. this._teleportationBorderColor = "#FFFFFF";
  70608. this._rotationAngle = 0;
  70609. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  70610. this._scene = scene;
  70611. if (!this._scene.activeCamera || isNaN(this._scene.activeCamera.position.x)) {
  70612. this._position = new BABYLON.Vector3(0, 2, 0);
  70613. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", new BABYLON.Vector3(0, 2, 0), scene);
  70614. }
  70615. else {
  70616. this._position = this._scene.activeCamera.position.clone();
  70617. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position, scene);
  70618. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  70619. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  70620. }
  70621. this._scene.activeCamera = this._deviceOrientationCamera;
  70622. this._canvas = scene.getEngine().getRenderingCanvas();
  70623. if (this._canvas) {
  70624. this._scene.activeCamera.attachControl(this._canvas);
  70625. }
  70626. if (webVROptions) {
  70627. if (webVROptions.useCustomVRButton) {
  70628. this._useCustomVRButton = true;
  70629. if (webVROptions.customVRButton) {
  70630. this._btnVR = webVROptions.customVRButton;
  70631. }
  70632. }
  70633. }
  70634. if (!this._useCustomVRButton) {
  70635. this._btnVR = document.createElement("BUTTON");
  70636. this._btnVR.className = "babylonVRicon";
  70637. this._btnVR.id = "babylonVRiconbtn";
  70638. this._btnVR.title = "Click to switch to VR";
  70639. 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) }";
  70640. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  70641. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  70642. // css += ".babylonVRicon.vrdisplaysupported { }";
  70643. // css += ".babylonVRicon.vrdisplayready { }";
  70644. // css += ".babylonVRicon.vrdisplayrequesting { }";
  70645. var style = document.createElement('style');
  70646. style.appendChild(document.createTextNode(css));
  70647. document.getElementsByTagName('head')[0].appendChild(style);
  70648. }
  70649. if (this._canvas) {
  70650. if (!this._useCustomVRButton) {
  70651. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  70652. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  70653. }
  70654. if (this._btnVR) {
  70655. this._btnVR.addEventListener("click", function () {
  70656. _this.enterVR();
  70657. });
  70658. }
  70659. window.addEventListener("resize", function () {
  70660. if (_this._canvas && !_this._useCustomVRButton) {
  70661. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  70662. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  70663. }
  70664. if (_this._fullscreenVRpresenting && _this._webVRready) {
  70665. _this.exitVR();
  70666. }
  70667. });
  70668. }
  70669. document.addEventListener("fullscreenchange", function () { _this._onFullscreenChange(); }, false);
  70670. document.addEventListener("mozfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  70671. document.addEventListener("webkitfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  70672. document.addEventListener("msfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  70673. if (!this._useCustomVRButton) {
  70674. document.body.appendChild(this._btnVR);
  70675. }
  70676. // Exiting VR mode using 'ESC' key on desktop
  70677. this._onKeyDown = function (event) {
  70678. if (event.keyCode === 27 && _this.isInVRMode()) {
  70679. _this.exitVR();
  70680. }
  70681. };
  70682. document.addEventListener("keydown", this._onKeyDown);
  70683. // Exiting VR mode double tapping the touch screen
  70684. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  70685. if (_this.isInVRMode()) {
  70686. _this.exitVR();
  70687. if (_this._fullscreenVRpresenting) {
  70688. _this._scene.getEngine().switchFullscreen(true);
  70689. }
  70690. }
  70691. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  70692. // Listen for WebVR display changes
  70693. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  70694. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  70695. this._onVRRequestPresentStart = function () {
  70696. _this._webVRrequesting = true;
  70697. _this.updateButtonVisibility();
  70698. };
  70699. this._onVRRequestPresentComplete = function (success) {
  70700. _this._webVRrequesting = false;
  70701. _this.updateButtonVisibility();
  70702. };
  70703. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  70704. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  70705. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  70706. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  70707. // Create the cameras
  70708. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  70709. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  70710. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  70711. this.updateButtonVisibility();
  70712. }
  70713. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  70714. get: function () {
  70715. return this._deviceOrientationCamera;
  70716. },
  70717. enumerable: true,
  70718. configurable: true
  70719. });
  70720. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  70721. // Based on the current WebVR support, returns the current VR camera used
  70722. get: function () {
  70723. if (this._webVRready) {
  70724. return this._webVRCamera;
  70725. }
  70726. else {
  70727. return this._vrDeviceOrientationCamera;
  70728. }
  70729. },
  70730. enumerable: true,
  70731. configurable: true
  70732. });
  70733. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  70734. get: function () {
  70735. return this._webVRCamera;
  70736. },
  70737. enumerable: true,
  70738. configurable: true
  70739. });
  70740. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  70741. get: function () {
  70742. return this._vrDeviceOrientationCamera;
  70743. },
  70744. enumerable: true,
  70745. configurable: true
  70746. });
  70747. // Raised when one of the controller has loaded successfully its associated default mesh
  70748. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  70749. if (webVRController.hand === "left") {
  70750. this._leftControllerReady = true;
  70751. if (this._teleportationRequested && !this._teleportationEnabledOnLeftController) {
  70752. this._enableTeleportationOnController(webVRController);
  70753. }
  70754. }
  70755. if (webVRController.hand === "right") {
  70756. this._rightControllerReady = true;
  70757. if (this._teleportationRequested && !this._teleportationEnabledOnRightController) {
  70758. this._enableTeleportationOnController(webVRController);
  70759. }
  70760. }
  70761. if (this.onControllerMeshLoaded) {
  70762. this.onControllerMeshLoaded(webVRController);
  70763. }
  70764. };
  70765. VRExperienceHelper.prototype._onFullscreenChange = function () {
  70766. if (document.fullscreen !== undefined) {
  70767. this._fullscreenVRpresenting = document.fullscreen;
  70768. }
  70769. else if (document.mozFullScreen !== undefined) {
  70770. this._fullscreenVRpresenting = document.mozFullScreen;
  70771. }
  70772. else if (document.webkitIsFullScreen !== undefined) {
  70773. this._fullscreenVRpresenting = document.webkitIsFullScreen;
  70774. }
  70775. else if (document.msIsFullScreen !== undefined) {
  70776. this._fullscreenVRpresenting = document.msIsFullScreen;
  70777. }
  70778. if (!this._fullscreenVRpresenting && this._canvas) {
  70779. this.exitVR();
  70780. if (!this._useCustomVRButton) {
  70781. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  70782. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  70783. }
  70784. }
  70785. };
  70786. VRExperienceHelper.prototype.isInVRMode = function () {
  70787. return this._webVRpresenting || this._fullscreenVRpresenting;
  70788. };
  70789. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  70790. var vrDisplay = this._scene.getEngine().getVRDevice();
  70791. if (vrDisplay) {
  70792. var wasPresenting = this._webVRpresenting;
  70793. // A VR display is connected
  70794. this._webVRpresenting = vrDisplay.isPresenting;
  70795. if (wasPresenting && !this._webVRpresenting)
  70796. this.exitVR();
  70797. }
  70798. else {
  70799. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  70800. }
  70801. this.updateButtonVisibility();
  70802. };
  70803. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  70804. this._webVRsupported = eventArgs.vrSupported;
  70805. this._webVRready = !!eventArgs.vrDisplay;
  70806. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  70807. this.updateButtonVisibility();
  70808. };
  70809. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  70810. if (!this._btnVR) {
  70811. return;
  70812. }
  70813. this._btnVR.className = "babylonVRicon";
  70814. if (this.isInVRMode()) {
  70815. this._btnVR.className += " vrdisplaypresenting";
  70816. }
  70817. else {
  70818. if (this._webVRready)
  70819. this._btnVR.className += " vrdisplayready";
  70820. if (this._webVRsupported)
  70821. this._btnVR.className += " vrdisplaysupported";
  70822. if (this._webVRrequesting)
  70823. this._btnVR.className += " vrdisplayrequesting";
  70824. }
  70825. };
  70826. /**
  70827. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  70828. * Otherwise, will use the fullscreen API.
  70829. */
  70830. VRExperienceHelper.prototype.enterVR = function () {
  70831. if (this._scene.activeCamera) {
  70832. this._position = this._scene.activeCamera.position.clone();
  70833. }
  70834. if (this.onEnteringVR) {
  70835. this.onEnteringVR();
  70836. }
  70837. if (this._webVRrequesting)
  70838. return;
  70839. // If WebVR is supported and a headset is connected
  70840. if (this._webVRready) {
  70841. if (!this._webVRpresenting) {
  70842. this._webVRCamera.position = this._position;
  70843. this._scene.activeCamera = this._webVRCamera;
  70844. this._scene.imageProcessingConfiguration.isEnabled = true;
  70845. }
  70846. }
  70847. else {
  70848. this._vrDeviceOrientationCamera.position = this._position;
  70849. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  70850. this._scene.getEngine().switchFullscreen(true);
  70851. this.updateButtonVisibility();
  70852. }
  70853. if (this._scene.activeCamera && this._canvas) {
  70854. this._scene.activeCamera.attachControl(this._canvas);
  70855. }
  70856. };
  70857. /**
  70858. * Attempt to exit VR, or fullscreen.
  70859. */
  70860. VRExperienceHelper.prototype.exitVR = function () {
  70861. if (this.onExitingVR) {
  70862. this.onExitingVR();
  70863. }
  70864. if (this._webVRpresenting) {
  70865. this._scene.getEngine().disableVR();
  70866. }
  70867. if (this._scene.activeCamera) {
  70868. this._position = this._scene.activeCamera.position.clone();
  70869. }
  70870. this._deviceOrientationCamera.position = this._position;
  70871. this._scene.activeCamera = this._deviceOrientationCamera;
  70872. this._scene.imageProcessingConfiguration.isEnabled = false;
  70873. if (this._canvas) {
  70874. this._scene.activeCamera.attachControl(this._canvas);
  70875. }
  70876. this.updateButtonVisibility();
  70877. };
  70878. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  70879. get: function () {
  70880. return this._position;
  70881. },
  70882. set: function (value) {
  70883. this._position = value;
  70884. if (this._scene.activeCamera) {
  70885. this._scene.activeCamera.position = value;
  70886. }
  70887. },
  70888. enumerable: true,
  70889. configurable: true
  70890. });
  70891. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  70892. var _this = this;
  70893. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  70894. this._teleportationRequested = true;
  70895. if (vrTeleportationOptions) {
  70896. if (vrTeleportationOptions.floorMeshName) {
  70897. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  70898. }
  70899. }
  70900. if (this._leftControllerReady && this._webVRCamera.leftController) {
  70901. this._enableTeleportationOnController(this._webVRCamera.leftController);
  70902. }
  70903. if (this._rightControllerReady && this._webVRCamera.rightController) {
  70904. this._enableTeleportationOnController(this._webVRCamera.rightController);
  70905. }
  70906. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera);
  70907. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  70908. this._scene.imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  70909. this._scene.imageProcessingConfiguration.vignetteEnabled = true;
  70910. this._scene.imageProcessingConfiguration.isEnabled = false;
  70911. this._createTeleportationCircles();
  70912. this.meshSelectionPredicate = function (mesh) {
  70913. if (mesh.name.indexOf(_this._floorMeshName) !== -1) {
  70914. return true;
  70915. }
  70916. return false;
  70917. };
  70918. this._scene.registerBeforeRender(function () {
  70919. _this._castRayAndSelectObject();
  70920. });
  70921. };
  70922. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  70923. var _this = this;
  70924. var controllerMesh = webVRController.mesh;
  70925. if (controllerMesh) {
  70926. var childMeshes = controllerMesh.getChildMeshes();
  70927. for (var i = 0; i < childMeshes.length; i++) {
  70928. if (childMeshes[i].name === "POINTING_POSE") {
  70929. controllerMesh = childMeshes[i];
  70930. break;
  70931. }
  70932. }
  70933. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 3, 0.004, 0.0001, 20, 1, this._scene, false);
  70934. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  70935. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  70936. laserPointerMaterial.alpha = 0.6;
  70937. laserPointer.material = laserPointerMaterial;
  70938. laserPointer.rotation.x = Math.PI / 2;
  70939. laserPointer.parent = controllerMesh;
  70940. laserPointer.position.z = -1.5;
  70941. laserPointer.position.y = 0;
  70942. laserPointer.isVisible = false;
  70943. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  70944. // Enabling / disabling laserPointer
  70945. if (stateObject.value === 1) {
  70946. laserPointer.isVisible = !laserPointer.isVisible;
  70947. }
  70948. });
  70949. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  70950. // on pressed
  70951. if (!_this._teleportationRequestInitiated) {
  70952. if (stateObject.y < -0.6) {
  70953. laserPointer.isVisible = true;
  70954. _this._teleportationRequestInitiated = true;
  70955. }
  70956. }
  70957. else {
  70958. if (stateObject.y > -0.4) {
  70959. if (_this._teleportationAllowed) {
  70960. _this._teleportCamera();
  70961. }
  70962. _this._teleportationRequestInitiated = false;
  70963. laserPointer.isVisible = false;
  70964. }
  70965. }
  70966. if (!_this._rotationLeftAsked) {
  70967. if (stateObject.x < -0.6) {
  70968. _this._rotationLeftAsked = true;
  70969. if (_this._rotationAllowed) {
  70970. _this._rotateCamera(false);
  70971. }
  70972. }
  70973. }
  70974. else {
  70975. if (stateObject.x > -0.4) {
  70976. _this._rotationLeftAsked = false;
  70977. }
  70978. }
  70979. if (!_this._rotationRightAsked) {
  70980. if (stateObject.x > 0.6) {
  70981. _this._rotationRightAsked = true;
  70982. if (_this._rotationAllowed) {
  70983. _this._rotateCamera(true);
  70984. }
  70985. }
  70986. }
  70987. else {
  70988. if (stateObject.x < 0.4) {
  70989. _this._rotationRightAsked = false;
  70990. }
  70991. }
  70992. });
  70993. }
  70994. };
  70995. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  70996. this._teleportationCircle = BABYLON.Mesh.CreateGround("teleportationCircle", 2, 2, 2, this._scene);
  70997. var length = 512;
  70998. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  70999. dynamicTexture.hasAlpha = true;
  71000. var context = dynamicTexture.getContext();
  71001. var centerX = length / 2;
  71002. var centerY = length / 2;
  71003. var radius = 200;
  71004. context.beginPath();
  71005. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  71006. context.fillStyle = this._teleportationFillColor;
  71007. context.fill();
  71008. context.lineWidth = 10;
  71009. context.strokeStyle = this._teleportationBorderColor;
  71010. context.stroke();
  71011. context.closePath();
  71012. dynamicTexture.update();
  71013. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  71014. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  71015. this._teleportationCircle.material = teleportationCircleMaterial;
  71016. var torus = BABYLON.Mesh.CreateTorus("torus", 0.75, 0.1, 25, this._scene, false);
  71017. torus.parent = this._teleportationCircle;
  71018. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  71019. var keys = [];
  71020. keys.push({
  71021. frame: 0,
  71022. value: 0
  71023. });
  71024. keys.push({
  71025. frame: 30,
  71026. value: 0.4
  71027. });
  71028. keys.push({
  71029. frame: 60,
  71030. value: 0
  71031. });
  71032. animationInnerCircle.setKeys(keys);
  71033. var easingFunction = new BABYLON.SineEase();
  71034. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  71035. animationInnerCircle.setEasingFunction(easingFunction);
  71036. torus.animations = [];
  71037. torus.animations.push(animationInnerCircle);
  71038. this._scene.beginAnimation(torus, 0, 60, true);
  71039. this._hideTeleportationCircle();
  71040. };
  71041. VRExperienceHelper.prototype._displayTeleportationCircle = function () {
  71042. this._teleportationCircle.isVisible = true;
  71043. this._teleportationCircle.getChildren()[0].isVisible = true;
  71044. };
  71045. VRExperienceHelper.prototype._hideTeleportationCircle = function () {
  71046. this._teleportationCircle.isVisible = false;
  71047. this._teleportationCircle.getChildren()[0].isVisible = false;
  71048. };
  71049. VRExperienceHelper.prototype._rotateCamera = function (right) {
  71050. var _this = this;
  71051. if (right) {
  71052. this._rotationAngle++;
  71053. }
  71054. else {
  71055. this._rotationAngle--;
  71056. }
  71057. this.currentVRCamera.animations = [];
  71058. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  71059. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  71060. var animationRotationKeys = [];
  71061. animationRotationKeys.push({
  71062. frame: 0,
  71063. value: this.currentVRCamera.rotationQuaternion
  71064. });
  71065. animationRotationKeys.push({
  71066. frame: 6,
  71067. value: target
  71068. });
  71069. animationRotation.setKeys(animationRotationKeys);
  71070. var easingFunction = new BABYLON.CircleEase();
  71071. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  71072. animationRotation.setEasingFunction(easingFunction);
  71073. this.currentVRCamera.animations.push(animationRotation);
  71074. this._postProcessMove.animations = [];
  71075. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  71076. var vignetteWeightKeys = [];
  71077. vignetteWeightKeys.push({
  71078. frame: 0,
  71079. value: 0
  71080. });
  71081. vignetteWeightKeys.push({
  71082. frame: 3,
  71083. value: 4
  71084. });
  71085. vignetteWeightKeys.push({
  71086. frame: 6,
  71087. value: 0
  71088. });
  71089. animationPP.setKeys(vignetteWeightKeys);
  71090. animationPP.setEasingFunction(easingFunction);
  71091. this._postProcessMove.animations.push(animationPP);
  71092. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  71093. var vignetteStretchKeys = [];
  71094. vignetteStretchKeys.push({
  71095. frame: 0,
  71096. value: 0
  71097. });
  71098. vignetteStretchKeys.push({
  71099. frame: 3,
  71100. value: 10
  71101. });
  71102. vignetteStretchKeys.push({
  71103. frame: 6,
  71104. value: 0
  71105. });
  71106. animationPP2.setKeys(vignetteStretchKeys);
  71107. animationPP2.setEasingFunction(easingFunction);
  71108. this._postProcessMove.animations.push(animationPP2);
  71109. this._scene.imageProcessingConfiguration.vignetteWeight = 0;
  71110. this._scene.imageProcessingConfiguration.vignetteStretch = 0;
  71111. this._scene.imageProcessingConfiguration.vignetteEnabled = true;
  71112. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  71113. _this._scene.imageProcessingConfiguration.vignetteEnabled = false;
  71114. });
  71115. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  71116. };
  71117. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (coordinates) {
  71118. this._teleportationAllowed = true;
  71119. if (this._teleportationRequestInitiated || this._xboxGamepadTeleportationRequestInitiated) {
  71120. this._displayTeleportationCircle();
  71121. }
  71122. else {
  71123. this._hideTeleportationCircle();
  71124. }
  71125. this._haloCenter.copyFrom(coordinates);
  71126. this._teleportationCircle.position = coordinates;
  71127. this._teleportationCircle.position.y += 0.001;
  71128. };
  71129. VRExperienceHelper.prototype._teleportCamera = function () {
  71130. var _this = this;
  71131. this.currentVRCamera.animations = [];
  71132. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position.x", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  71133. var animationCameraTeleportationKeys = [];
  71134. animationCameraTeleportationKeys.push({
  71135. frame: 0,
  71136. value: this.currentVRCamera.position.x
  71137. });
  71138. animationCameraTeleportationKeys.push({
  71139. frame: 11,
  71140. value: this._haloCenter.x
  71141. });
  71142. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  71143. var easingFunction = new BABYLON.CircleEase();
  71144. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  71145. animationCameraTeleportation.setEasingFunction(easingFunction);
  71146. this.currentVRCamera.animations.push(animationCameraTeleportation);
  71147. var animationZoomIn2 = new BABYLON.Animation("animationZoomIn", "position.z", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  71148. var keys2 = [];
  71149. keys2.push({
  71150. frame: 0,
  71151. value: this.currentVRCamera.position.z
  71152. });
  71153. keys2.push({
  71154. frame: 11,
  71155. value: this._haloCenter.z
  71156. });
  71157. animationZoomIn2.setKeys(keys2);
  71158. animationZoomIn2.setEasingFunction(easingFunction);
  71159. this.currentVRCamera.animations.push(animationZoomIn2);
  71160. this._postProcessMove.animations = [];
  71161. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  71162. var vignetteWeightKeys = [];
  71163. vignetteWeightKeys.push({
  71164. frame: 0,
  71165. value: 0
  71166. });
  71167. vignetteWeightKeys.push({
  71168. frame: 5,
  71169. value: 8
  71170. });
  71171. vignetteWeightKeys.push({
  71172. frame: 11,
  71173. value: 0
  71174. });
  71175. animationPP.setKeys(vignetteWeightKeys);
  71176. this._postProcessMove.animations.push(animationPP);
  71177. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  71178. var vignetteStretchKeys = [];
  71179. vignetteStretchKeys.push({
  71180. frame: 0,
  71181. value: 0
  71182. });
  71183. vignetteStretchKeys.push({
  71184. frame: 5,
  71185. value: 10
  71186. });
  71187. vignetteStretchKeys.push({
  71188. frame: 11,
  71189. value: 0
  71190. });
  71191. animationPP2.setKeys(vignetteStretchKeys);
  71192. this._postProcessMove.animations.push(animationPP2);
  71193. this._scene.imageProcessingConfiguration.vignetteWeight = 8;
  71194. this._scene.imageProcessingConfiguration.vignetteStretch = 10;
  71195. this._scene.imageProcessingConfiguration.vignetteEnabled = true;
  71196. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  71197. _this._scene.imageProcessingConfiguration.vignetteEnabled = false;
  71198. });
  71199. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1);
  71200. };
  71201. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  71202. var ray;
  71203. if (!this.currentVRCamera.rightController) {
  71204. ray = this.currentVRCamera.getForwardRay();
  71205. }
  71206. else {
  71207. ray = this.currentVRCamera.rightController.getForwardRay();
  71208. }
  71209. var hit = this._scene.pickWithRay(ray, this.meshSelectionPredicate);
  71210. if (this._rayHelper) {
  71211. this._rayHelper.dispose();
  71212. }
  71213. if (this.currentVRCamera.rightController) {
  71214. //if (target) target.isVisible = false;
  71215. this._rayHelper = BABYLON.RayHelper.CreateAndShow(ray, this._scene, new BABYLON.Color3(0.7, 0.7, 0.7));
  71216. }
  71217. if (hit && hit.pickedMesh) {
  71218. // The object selected is the floor, we're in a teleportation scenario
  71219. if (hit.pickedMesh.name.indexOf(this._floorMeshName) !== -1 && hit.pickedPoint) {
  71220. this._moveTeleportationSelectorTo(hit.pickedPoint);
  71221. return;
  71222. }
  71223. // If not, we're in a selection scenario
  71224. this._hideTeleportationCircle();
  71225. this._teleportationAllowed = false;
  71226. //currentMeshSelected = hit.pickedMesh;
  71227. }
  71228. else {
  71229. this._teleportationAllowed = false;
  71230. this._hideTeleportationCircle();
  71231. }
  71232. };
  71233. VRExperienceHelper.prototype.dispose = function () {
  71234. if (this.isInVRMode()) {
  71235. this.exitVR();
  71236. }
  71237. this._deviceOrientationCamera.dispose();
  71238. if (this._passProcessMove) {
  71239. this._passProcessMove.dispose();
  71240. }
  71241. if (this._postProcessMove) {
  71242. this._postProcessMove.dispose();
  71243. }
  71244. if (this._webVRCamera) {
  71245. this._webVRCamera.dispose();
  71246. }
  71247. if (this._vrDeviceOrientationCamera) {
  71248. this._vrDeviceOrientationCamera.dispose();
  71249. }
  71250. if (!this._useCustomVRButton) {
  71251. document.body.removeChild(this._btnVR);
  71252. }
  71253. document.removeEventListener("keydown", this._onKeyDown);
  71254. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  71255. };
  71256. VRExperienceHelper.prototype.getClassName = function () {
  71257. return "VRExperienceHelper";
  71258. };
  71259. return VRExperienceHelper;
  71260. }());
  71261. BABYLON.VRExperienceHelper = VRExperienceHelper;
  71262. })(BABYLON || (BABYLON = {}));
  71263. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  71264. // Mainly based on these 2 articles :
  71265. // 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
  71266. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  71267. var BABYLON;
  71268. (function (BABYLON) {
  71269. var JoystickAxis;
  71270. (function (JoystickAxis) {
  71271. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  71272. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  71273. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  71274. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  71275. var VirtualJoystick = /** @class */ (function () {
  71276. function VirtualJoystick(leftJoystick) {
  71277. var _this = this;
  71278. if (leftJoystick) {
  71279. this._leftJoystick = true;
  71280. }
  71281. else {
  71282. this._leftJoystick = false;
  71283. }
  71284. VirtualJoystick._globalJoystickIndex++;
  71285. // By default left & right arrow keys are moving the X
  71286. // and up & down keys are moving the Y
  71287. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  71288. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  71289. this.reverseLeftRight = false;
  71290. this.reverseUpDown = false;
  71291. // collections of pointers
  71292. this._touches = new BABYLON.StringDictionary();
  71293. this.deltaPosition = BABYLON.Vector3.Zero();
  71294. this._joystickSensibility = 25;
  71295. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  71296. this._onResize = function (evt) {
  71297. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  71298. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  71299. if (VirtualJoystick.vjCanvas) {
  71300. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  71301. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  71302. }
  71303. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  71304. };
  71305. // injecting a canvas element on top of the canvas 3D game
  71306. if (!VirtualJoystick.vjCanvas) {
  71307. window.addEventListener("resize", this._onResize, false);
  71308. VirtualJoystick.vjCanvas = document.createElement("canvas");
  71309. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  71310. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  71311. VirtualJoystick.vjCanvas.width = window.innerWidth;
  71312. VirtualJoystick.vjCanvas.height = window.innerHeight;
  71313. VirtualJoystick.vjCanvas.style.width = "100%";
  71314. VirtualJoystick.vjCanvas.style.height = "100%";
  71315. VirtualJoystick.vjCanvas.style.position = "absolute";
  71316. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  71317. VirtualJoystick.vjCanvas.style.top = "0px";
  71318. VirtualJoystick.vjCanvas.style.left = "0px";
  71319. VirtualJoystick.vjCanvas.style.zIndex = "5";
  71320. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  71321. // Support for jQuery PEP polyfill
  71322. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  71323. var context = VirtualJoystick.vjCanvas.getContext('2d');
  71324. if (!context) {
  71325. throw new Error("Unable to create canvas for virtual joystick");
  71326. }
  71327. VirtualJoystick.vjCanvasContext = context;
  71328. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  71329. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  71330. document.body.appendChild(VirtualJoystick.vjCanvas);
  71331. }
  71332. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  71333. this.pressed = false;
  71334. // default joystick color
  71335. this._joystickColor = "cyan";
  71336. this._joystickPointerID = -1;
  71337. // current joystick position
  71338. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  71339. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  71340. // origin joystick position
  71341. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  71342. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  71343. this._onPointerDownHandlerRef = function (evt) {
  71344. _this._onPointerDown(evt);
  71345. };
  71346. this._onPointerMoveHandlerRef = function (evt) {
  71347. _this._onPointerMove(evt);
  71348. };
  71349. this._onPointerUpHandlerRef = function (evt) {
  71350. _this._onPointerUp(evt);
  71351. };
  71352. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  71353. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  71354. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  71355. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  71356. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  71357. evt.preventDefault(); // Disables system menu
  71358. }, false);
  71359. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  71360. }
  71361. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  71362. this._joystickSensibility = newJoystickSensibility;
  71363. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  71364. };
  71365. VirtualJoystick.prototype._onPointerDown = function (e) {
  71366. var positionOnScreenCondition;
  71367. e.preventDefault();
  71368. if (this._leftJoystick === true) {
  71369. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  71370. }
  71371. else {
  71372. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  71373. }
  71374. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  71375. // First contact will be dedicated to the virtual joystick
  71376. this._joystickPointerID = e.pointerId;
  71377. this._joystickPointerStartPos.x = e.clientX;
  71378. this._joystickPointerStartPos.y = e.clientY;
  71379. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  71380. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  71381. this._deltaJoystickVector.x = 0;
  71382. this._deltaJoystickVector.y = 0;
  71383. this.pressed = true;
  71384. this._touches.add(e.pointerId.toString(), e);
  71385. }
  71386. else {
  71387. // You can only trigger the action buttons with a joystick declared
  71388. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  71389. this._action();
  71390. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  71391. }
  71392. }
  71393. };
  71394. VirtualJoystick.prototype._onPointerMove = function (e) {
  71395. // If the current pointer is the one associated to the joystick (first touch contact)
  71396. if (this._joystickPointerID == e.pointerId) {
  71397. this._joystickPointerPos.x = e.clientX;
  71398. this._joystickPointerPos.y = e.clientY;
  71399. this._deltaJoystickVector = this._joystickPointerPos.clone();
  71400. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  71401. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  71402. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  71403. switch (this._axisTargetedByLeftAndRight) {
  71404. case JoystickAxis.X:
  71405. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  71406. break;
  71407. case JoystickAxis.Y:
  71408. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  71409. break;
  71410. case JoystickAxis.Z:
  71411. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  71412. break;
  71413. }
  71414. var directionUpDown = this.reverseUpDown ? 1 : -1;
  71415. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  71416. switch (this._axisTargetedByUpAndDown) {
  71417. case JoystickAxis.X:
  71418. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  71419. break;
  71420. case JoystickAxis.Y:
  71421. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  71422. break;
  71423. case JoystickAxis.Z:
  71424. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  71425. break;
  71426. }
  71427. }
  71428. else {
  71429. var data = this._touches.get(e.pointerId.toString());
  71430. if (data) {
  71431. data.x = e.clientX;
  71432. data.y = e.clientY;
  71433. }
  71434. }
  71435. };
  71436. VirtualJoystick.prototype._onPointerUp = function (e) {
  71437. if (this._joystickPointerID == e.pointerId) {
  71438. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  71439. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  71440. this._joystickPointerID = -1;
  71441. this.pressed = false;
  71442. }
  71443. else {
  71444. var touch = this._touches.get(e.pointerId.toString());
  71445. if (touch) {
  71446. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  71447. }
  71448. }
  71449. this._deltaJoystickVector.x = 0;
  71450. this._deltaJoystickVector.y = 0;
  71451. this._touches.remove(e.pointerId.toString());
  71452. };
  71453. /**
  71454. * Change the color of the virtual joystick
  71455. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  71456. */
  71457. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  71458. this._joystickColor = newColor;
  71459. };
  71460. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  71461. this._action = action;
  71462. };
  71463. // Define which axis you'd like to control for left & right
  71464. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  71465. switch (axis) {
  71466. case JoystickAxis.X:
  71467. case JoystickAxis.Y:
  71468. case JoystickAxis.Z:
  71469. this._axisTargetedByLeftAndRight = axis;
  71470. break;
  71471. default:
  71472. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  71473. break;
  71474. }
  71475. };
  71476. // Define which axis you'd like to control for up & down
  71477. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  71478. switch (axis) {
  71479. case JoystickAxis.X:
  71480. case JoystickAxis.Y:
  71481. case JoystickAxis.Z:
  71482. this._axisTargetedByUpAndDown = axis;
  71483. break;
  71484. default:
  71485. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  71486. break;
  71487. }
  71488. };
  71489. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  71490. var _this = this;
  71491. if (this.pressed) {
  71492. this._touches.forEach(function (key, touch) {
  71493. if (touch.pointerId === _this._joystickPointerID) {
  71494. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  71495. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  71496. VirtualJoystick.vjCanvasContext.beginPath();
  71497. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  71498. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  71499. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  71500. VirtualJoystick.vjCanvasContext.stroke();
  71501. VirtualJoystick.vjCanvasContext.closePath();
  71502. VirtualJoystick.vjCanvasContext.beginPath();
  71503. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  71504. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  71505. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  71506. VirtualJoystick.vjCanvasContext.stroke();
  71507. VirtualJoystick.vjCanvasContext.closePath();
  71508. VirtualJoystick.vjCanvasContext.beginPath();
  71509. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  71510. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  71511. VirtualJoystick.vjCanvasContext.stroke();
  71512. VirtualJoystick.vjCanvasContext.closePath();
  71513. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  71514. }
  71515. else {
  71516. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  71517. VirtualJoystick.vjCanvasContext.beginPath();
  71518. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  71519. VirtualJoystick.vjCanvasContext.beginPath();
  71520. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  71521. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  71522. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  71523. VirtualJoystick.vjCanvasContext.stroke();
  71524. VirtualJoystick.vjCanvasContext.closePath();
  71525. touch.prevX = touch.x;
  71526. touch.prevY = touch.y;
  71527. }
  71528. ;
  71529. });
  71530. }
  71531. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  71532. };
  71533. VirtualJoystick.prototype.releaseCanvas = function () {
  71534. if (VirtualJoystick.vjCanvas) {
  71535. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  71536. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  71537. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  71538. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  71539. window.removeEventListener("resize", this._onResize);
  71540. document.body.removeChild(VirtualJoystick.vjCanvas);
  71541. VirtualJoystick.vjCanvas = null;
  71542. }
  71543. };
  71544. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  71545. VirtualJoystick._globalJoystickIndex = 0;
  71546. return VirtualJoystick;
  71547. }());
  71548. BABYLON.VirtualJoystick = VirtualJoystick;
  71549. })(BABYLON || (BABYLON = {}));
  71550. //# sourceMappingURL=babylon.virtualJoystick.js.map
  71551. var BABYLON;
  71552. (function (BABYLON) {
  71553. // We're mainly based on the logic defined into the FreeCamera code
  71554. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  71555. __extends(VirtualJoysticksCamera, _super);
  71556. function VirtualJoysticksCamera(name, position, scene) {
  71557. var _this = _super.call(this, name, position, scene) || this;
  71558. _this.inputs.addVirtualJoystick();
  71559. return _this;
  71560. }
  71561. VirtualJoysticksCamera.prototype.getClassName = function () {
  71562. return "VirtualJoysticksCamera";
  71563. };
  71564. return VirtualJoysticksCamera;
  71565. }(BABYLON.FreeCamera));
  71566. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  71567. })(BABYLON || (BABYLON = {}));
  71568. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  71569. var BABYLON;
  71570. (function (BABYLON) {
  71571. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  71572. function FreeCameraVirtualJoystickInput() {
  71573. }
  71574. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  71575. return this._leftjoystick;
  71576. };
  71577. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  71578. return this._rightjoystick;
  71579. };
  71580. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  71581. if (this._leftjoystick) {
  71582. var camera = this.camera;
  71583. var speed = camera._computeLocalCameraSpeed() * 50;
  71584. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  71585. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  71586. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  71587. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  71588. if (!this._leftjoystick.pressed) {
  71589. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  71590. }
  71591. if (!this._rightjoystick.pressed) {
  71592. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  71593. }
  71594. }
  71595. };
  71596. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  71597. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  71598. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  71599. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  71600. this._leftjoystick.setJoystickSensibility(0.15);
  71601. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  71602. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  71603. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  71604. this._rightjoystick.reverseUpDown = true;
  71605. this._rightjoystick.setJoystickSensibility(0.05);
  71606. this._rightjoystick.setJoystickColor("yellow");
  71607. };
  71608. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  71609. this._leftjoystick.releaseCanvas();
  71610. this._rightjoystick.releaseCanvas();
  71611. };
  71612. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  71613. return "FreeCameraVirtualJoystickInput";
  71614. };
  71615. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  71616. return "virtualJoystick";
  71617. };
  71618. return FreeCameraVirtualJoystickInput;
  71619. }());
  71620. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  71621. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  71622. })(BABYLON || (BABYLON = {}));
  71623. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  71624. var BABYLON;
  71625. (function (BABYLON) {
  71626. var SimplificationSettings = /** @class */ (function () {
  71627. function SimplificationSettings(quality, distance, optimizeMesh) {
  71628. this.quality = quality;
  71629. this.distance = distance;
  71630. this.optimizeMesh = optimizeMesh;
  71631. }
  71632. return SimplificationSettings;
  71633. }());
  71634. BABYLON.SimplificationSettings = SimplificationSettings;
  71635. var SimplificationQueue = /** @class */ (function () {
  71636. function SimplificationQueue() {
  71637. this.running = false;
  71638. this._simplificationArray = [];
  71639. }
  71640. SimplificationQueue.prototype.addTask = function (task) {
  71641. this._simplificationArray.push(task);
  71642. };
  71643. SimplificationQueue.prototype.executeNext = function () {
  71644. var task = this._simplificationArray.pop();
  71645. if (task) {
  71646. this.running = true;
  71647. this.runSimplification(task);
  71648. }
  71649. else {
  71650. this.running = false;
  71651. }
  71652. };
  71653. SimplificationQueue.prototype.runSimplification = function (task) {
  71654. var _this = this;
  71655. if (task.parallelProcessing) {
  71656. //parallel simplifier
  71657. task.settings.forEach(function (setting) {
  71658. var simplifier = _this.getSimplifier(task);
  71659. simplifier.simplify(setting, function (newMesh) {
  71660. task.mesh.addLODLevel(setting.distance, newMesh);
  71661. newMesh.isVisible = true;
  71662. //check if it is the last
  71663. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  71664. //all done, run the success callback.
  71665. task.successCallback();
  71666. }
  71667. _this.executeNext();
  71668. });
  71669. });
  71670. }
  71671. else {
  71672. //single simplifier.
  71673. var simplifier = this.getSimplifier(task);
  71674. var runDecimation = function (setting, callback) {
  71675. simplifier.simplify(setting, function (newMesh) {
  71676. task.mesh.addLODLevel(setting.distance, newMesh);
  71677. newMesh.isVisible = true;
  71678. //run the next quality level
  71679. callback();
  71680. });
  71681. };
  71682. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  71683. runDecimation(task.settings[loop.index], function () {
  71684. loop.executeNext();
  71685. });
  71686. }, function () {
  71687. //execution ended, run the success callback.
  71688. if (task.successCallback) {
  71689. task.successCallback();
  71690. }
  71691. _this.executeNext();
  71692. });
  71693. }
  71694. };
  71695. SimplificationQueue.prototype.getSimplifier = function (task) {
  71696. switch (task.simplificationType) {
  71697. case SimplificationType.QUADRATIC:
  71698. default:
  71699. return new QuadraticErrorSimplification(task.mesh);
  71700. }
  71701. };
  71702. return SimplificationQueue;
  71703. }());
  71704. BABYLON.SimplificationQueue = SimplificationQueue;
  71705. /**
  71706. * The implemented types of simplification.
  71707. * At the moment only Quadratic Error Decimation is implemented.
  71708. */
  71709. var SimplificationType;
  71710. (function (SimplificationType) {
  71711. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  71712. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  71713. var DecimationTriangle = /** @class */ (function () {
  71714. function DecimationTriangle(vertices) {
  71715. this.vertices = vertices;
  71716. this.error = new Array(4);
  71717. this.deleted = false;
  71718. this.isDirty = false;
  71719. this.deletePending = false;
  71720. this.borderFactor = 0;
  71721. }
  71722. return DecimationTriangle;
  71723. }());
  71724. BABYLON.DecimationTriangle = DecimationTriangle;
  71725. var DecimationVertex = /** @class */ (function () {
  71726. function DecimationVertex(position, id) {
  71727. this.position = position;
  71728. this.id = id;
  71729. this.isBorder = true;
  71730. this.q = new QuadraticMatrix();
  71731. this.triangleCount = 0;
  71732. this.triangleStart = 0;
  71733. this.originalOffsets = [];
  71734. }
  71735. DecimationVertex.prototype.updatePosition = function (newPosition) {
  71736. this.position.copyFrom(newPosition);
  71737. };
  71738. return DecimationVertex;
  71739. }());
  71740. BABYLON.DecimationVertex = DecimationVertex;
  71741. var QuadraticMatrix = /** @class */ (function () {
  71742. function QuadraticMatrix(data) {
  71743. this.data = new Array(10);
  71744. for (var i = 0; i < 10; ++i) {
  71745. if (data && data[i]) {
  71746. this.data[i] = data[i];
  71747. }
  71748. else {
  71749. this.data[i] = 0;
  71750. }
  71751. }
  71752. }
  71753. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  71754. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  71755. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  71756. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  71757. return det;
  71758. };
  71759. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  71760. for (var i = 0; i < 10; ++i) {
  71761. this.data[i] += matrix.data[i];
  71762. }
  71763. };
  71764. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  71765. for (var i = 0; i < 10; ++i) {
  71766. this.data[i] += data[i];
  71767. }
  71768. };
  71769. QuadraticMatrix.prototype.add = function (matrix) {
  71770. var m = new QuadraticMatrix();
  71771. for (var i = 0; i < 10; ++i) {
  71772. m.data[i] = this.data[i] + matrix.data[i];
  71773. }
  71774. return m;
  71775. };
  71776. QuadraticMatrix.FromData = function (a, b, c, d) {
  71777. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  71778. };
  71779. //returning an array to avoid garbage collection
  71780. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  71781. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  71782. };
  71783. return QuadraticMatrix;
  71784. }());
  71785. BABYLON.QuadraticMatrix = QuadraticMatrix;
  71786. var Reference = /** @class */ (function () {
  71787. function Reference(vertexId, triangleId) {
  71788. this.vertexId = vertexId;
  71789. this.triangleId = triangleId;
  71790. }
  71791. return Reference;
  71792. }());
  71793. BABYLON.Reference = Reference;
  71794. /**
  71795. * An implementation of the Quadratic Error simplification algorithm.
  71796. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  71797. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  71798. * @author RaananW
  71799. */
  71800. var QuadraticErrorSimplification = /** @class */ (function () {
  71801. function QuadraticErrorSimplification(_mesh) {
  71802. this._mesh = _mesh;
  71803. this.syncIterations = 5000;
  71804. this.aggressiveness = 7;
  71805. this.decimationIterations = 100;
  71806. this.boundingBoxEpsilon = BABYLON.Epsilon;
  71807. }
  71808. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  71809. var _this = this;
  71810. this.initDecimatedMesh();
  71811. //iterating through the submeshes array, one after the other.
  71812. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  71813. _this.initWithMesh(loop.index, function () {
  71814. _this.runDecimation(settings, loop.index, function () {
  71815. loop.executeNext();
  71816. });
  71817. }, settings.optimizeMesh);
  71818. }, function () {
  71819. setTimeout(function () {
  71820. successCallback(_this._reconstructedMesh);
  71821. }, 0);
  71822. });
  71823. };
  71824. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  71825. var _this = this;
  71826. var targetCount = ~~(this.triangles.length * settings.quality);
  71827. var deletedTriangles = 0;
  71828. var triangleCount = this.triangles.length;
  71829. var iterationFunction = function (iteration, callback) {
  71830. setTimeout(function () {
  71831. if (iteration % 5 === 0) {
  71832. _this.updateMesh(iteration === 0);
  71833. }
  71834. for (var i = 0; i < _this.triangles.length; ++i) {
  71835. _this.triangles[i].isDirty = false;
  71836. }
  71837. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  71838. var trianglesIterator = function (i) {
  71839. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  71840. var t = _this.triangles[tIdx];
  71841. if (!t)
  71842. return;
  71843. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  71844. return;
  71845. }
  71846. for (var j = 0; j < 3; ++j) {
  71847. if (t.error[j] < threshold) {
  71848. var deleted0 = [];
  71849. var deleted1 = [];
  71850. var v0 = t.vertices[j];
  71851. var v1 = t.vertices[(j + 1) % 3];
  71852. if (v0.isBorder || v1.isBorder)
  71853. continue;
  71854. var p = BABYLON.Vector3.Zero();
  71855. var n = BABYLON.Vector3.Zero();
  71856. var uv = BABYLON.Vector2.Zero();
  71857. var color = new BABYLON.Color4(0, 0, 0, 1);
  71858. _this.calculateError(v0, v1, p, n, uv, color);
  71859. var delTr = new Array();
  71860. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  71861. continue;
  71862. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  71863. continue;
  71864. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  71865. continue;
  71866. var uniqueArray = new Array();
  71867. delTr.forEach(function (deletedT) {
  71868. if (uniqueArray.indexOf(deletedT) === -1) {
  71869. deletedT.deletePending = true;
  71870. uniqueArray.push(deletedT);
  71871. }
  71872. });
  71873. if (uniqueArray.length % 2 !== 0) {
  71874. continue;
  71875. }
  71876. v0.q = v1.q.add(v0.q);
  71877. v0.updatePosition(p);
  71878. var tStart = _this.references.length;
  71879. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  71880. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  71881. var tCount = _this.references.length - tStart;
  71882. if (tCount <= v0.triangleCount) {
  71883. if (tCount) {
  71884. for (var c = 0; c < tCount; c++) {
  71885. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  71886. }
  71887. }
  71888. }
  71889. else {
  71890. v0.triangleStart = tStart;
  71891. }
  71892. v0.triangleCount = tCount;
  71893. break;
  71894. }
  71895. }
  71896. };
  71897. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  71898. }, 0);
  71899. };
  71900. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  71901. if (triangleCount - deletedTriangles <= targetCount)
  71902. loop.breakLoop();
  71903. else {
  71904. iterationFunction(loop.index, function () {
  71905. loop.executeNext();
  71906. });
  71907. }
  71908. }, function () {
  71909. setTimeout(function () {
  71910. //reconstruct this part of the mesh
  71911. _this.reconstructMesh(submeshIndex);
  71912. successCallback();
  71913. }, 0);
  71914. });
  71915. };
  71916. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  71917. var _this = this;
  71918. this.vertices = [];
  71919. this.triangles = [];
  71920. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  71921. var indices = this._mesh.getIndices();
  71922. var submesh = this._mesh.subMeshes[submeshIndex];
  71923. var findInVertices = function (positionToSearch) {
  71924. if (optimizeMesh) {
  71925. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  71926. if (_this.vertices[ii].position.equals(positionToSearch)) {
  71927. return _this.vertices[ii];
  71928. }
  71929. }
  71930. }
  71931. return null;
  71932. };
  71933. var vertexReferences = [];
  71934. var vertexInit = function (i) {
  71935. if (!positionData) {
  71936. return;
  71937. }
  71938. var offset = i + submesh.verticesStart;
  71939. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  71940. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  71941. vertex.originalOffsets.push(offset);
  71942. if (vertex.id === _this.vertices.length) {
  71943. _this.vertices.push(vertex);
  71944. }
  71945. vertexReferences.push(vertex.id);
  71946. };
  71947. //var totalVertices = mesh.getTotalVertices();
  71948. var totalVertices = submesh.verticesCount;
  71949. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  71950. var indicesInit = function (i) {
  71951. if (!indices) {
  71952. return;
  71953. }
  71954. var offset = (submesh.indexStart / 3) + i;
  71955. var pos = (offset * 3);
  71956. var i0 = indices[pos + 0];
  71957. var i1 = indices[pos + 1];
  71958. var i2 = indices[pos + 2];
  71959. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  71960. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  71961. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  71962. var triangle = new DecimationTriangle([v0, v1, v2]);
  71963. triangle.originalOffset = pos;
  71964. _this.triangles.push(triangle);
  71965. };
  71966. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  71967. _this.init(callback);
  71968. });
  71969. });
  71970. };
  71971. QuadraticErrorSimplification.prototype.init = function (callback) {
  71972. var _this = this;
  71973. var triangleInit1 = function (i) {
  71974. var t = _this.triangles[i];
  71975. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  71976. for (var j = 0; j < 3; j++) {
  71977. 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))));
  71978. }
  71979. };
  71980. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  71981. var triangleInit2 = function (i) {
  71982. var t = _this.triangles[i];
  71983. for (var j = 0; j < 3; ++j) {
  71984. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  71985. }
  71986. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  71987. };
  71988. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  71989. callback();
  71990. });
  71991. });
  71992. };
  71993. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  71994. var newTriangles = [];
  71995. var i;
  71996. for (i = 0; i < this.vertices.length; ++i) {
  71997. this.vertices[i].triangleCount = 0;
  71998. }
  71999. var t;
  72000. var j;
  72001. for (i = 0; i < this.triangles.length; ++i) {
  72002. if (!this.triangles[i].deleted) {
  72003. t = this.triangles[i];
  72004. for (j = 0; j < 3; ++j) {
  72005. t.vertices[j].triangleCount = 1;
  72006. }
  72007. newTriangles.push(t);
  72008. }
  72009. }
  72010. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  72011. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  72012. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  72013. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  72014. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  72015. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  72016. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  72017. var vertexCount = 0;
  72018. for (i = 0; i < this.vertices.length; ++i) {
  72019. var vertex = this.vertices[i];
  72020. vertex.id = vertexCount;
  72021. if (vertex.triangleCount) {
  72022. vertex.originalOffsets.forEach(function (originalOffset) {
  72023. if (!normalData) {
  72024. return;
  72025. }
  72026. newPositionData.push(vertex.position.x);
  72027. newPositionData.push(vertex.position.y);
  72028. newPositionData.push(vertex.position.z);
  72029. newNormalData.push(normalData[originalOffset * 3]);
  72030. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  72031. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  72032. if (uvs && uvs.length) {
  72033. newUVsData.push(uvs[(originalOffset * 2)]);
  72034. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  72035. }
  72036. else if (colorsData && colorsData.length) {
  72037. newColorsData.push(colorsData[(originalOffset * 4)]);
  72038. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  72039. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  72040. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  72041. }
  72042. ++vertexCount;
  72043. });
  72044. }
  72045. }
  72046. var startingIndex = this._reconstructedMesh.getTotalIndices();
  72047. var startingVertex = this._reconstructedMesh.getTotalVertices();
  72048. var submeshesArray = this._reconstructedMesh.subMeshes;
  72049. this._reconstructedMesh.subMeshes = [];
  72050. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  72051. var originalIndices = this._mesh.getIndices();
  72052. for (i = 0; i < newTriangles.length; ++i) {
  72053. t = newTriangles[i]; //now get the new referencing point for each vertex
  72054. [0, 1, 2].forEach(function (idx) {
  72055. var id = originalIndices[t.originalOffset + idx];
  72056. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  72057. if (offset < 0)
  72058. offset = 0;
  72059. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  72060. });
  72061. }
  72062. //overwriting the old vertex buffers and indices.
  72063. this._reconstructedMesh.setIndices(newIndicesArray);
  72064. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  72065. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  72066. if (newUVsData.length > 0)
  72067. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  72068. if (newColorsData.length > 0)
  72069. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  72070. //create submesh
  72071. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  72072. if (submeshIndex > 0) {
  72073. this._reconstructedMesh.subMeshes = [];
  72074. submeshesArray.forEach(function (submesh) {
  72075. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  72076. });
  72077. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  72078. }
  72079. };
  72080. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  72081. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  72082. this._reconstructedMesh.material = this._mesh.material;
  72083. this._reconstructedMesh.parent = this._mesh.parent;
  72084. this._reconstructedMesh.isVisible = false;
  72085. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  72086. };
  72087. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  72088. for (var i = 0; i < vertex1.triangleCount; ++i) {
  72089. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  72090. if (t.deleted)
  72091. continue;
  72092. var s = this.references[vertex1.triangleStart + i].vertexId;
  72093. var v1 = t.vertices[(s + 1) % 3];
  72094. var v2 = t.vertices[(s + 2) % 3];
  72095. if ((v1 === vertex2 || v2 === vertex2)) {
  72096. deletedArray[i] = true;
  72097. delTr.push(t);
  72098. continue;
  72099. }
  72100. var d1 = v1.position.subtract(point);
  72101. d1 = d1.normalize();
  72102. var d2 = v2.position.subtract(point);
  72103. d2 = d2.normalize();
  72104. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  72105. return true;
  72106. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  72107. deletedArray[i] = false;
  72108. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  72109. return true;
  72110. }
  72111. return false;
  72112. };
  72113. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  72114. var newDeleted = deletedTriangles;
  72115. for (var i = 0; i < vertex.triangleCount; ++i) {
  72116. var ref = this.references[vertex.triangleStart + i];
  72117. var t = this.triangles[ref.triangleId];
  72118. if (t.deleted)
  72119. continue;
  72120. if (deletedArray[i] && t.deletePending) {
  72121. t.deleted = true;
  72122. newDeleted++;
  72123. continue;
  72124. }
  72125. t.vertices[ref.vertexId] = origVertex;
  72126. t.isDirty = true;
  72127. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  72128. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  72129. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  72130. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  72131. this.references.push(ref);
  72132. }
  72133. return newDeleted;
  72134. };
  72135. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  72136. for (var i = 0; i < this.vertices.length; ++i) {
  72137. var vCount = [];
  72138. var vId = [];
  72139. var v = this.vertices[i];
  72140. var j;
  72141. for (j = 0; j < v.triangleCount; ++j) {
  72142. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  72143. for (var ii = 0; ii < 3; ii++) {
  72144. var ofs = 0;
  72145. var vv = triangle.vertices[ii];
  72146. while (ofs < vCount.length) {
  72147. if (vId[ofs] === vv.id)
  72148. break;
  72149. ++ofs;
  72150. }
  72151. if (ofs === vCount.length) {
  72152. vCount.push(1);
  72153. vId.push(vv.id);
  72154. }
  72155. else {
  72156. vCount[ofs]++;
  72157. }
  72158. }
  72159. }
  72160. for (j = 0; j < vCount.length; ++j) {
  72161. if (vCount[j] === 1) {
  72162. this.vertices[vId[j]].isBorder = true;
  72163. }
  72164. else {
  72165. this.vertices[vId[j]].isBorder = false;
  72166. }
  72167. }
  72168. }
  72169. };
  72170. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  72171. if (identifyBorders === void 0) { identifyBorders = false; }
  72172. var i;
  72173. if (!identifyBorders) {
  72174. var newTrianglesVector = [];
  72175. for (i = 0; i < this.triangles.length; ++i) {
  72176. if (!this.triangles[i].deleted) {
  72177. newTrianglesVector.push(this.triangles[i]);
  72178. }
  72179. }
  72180. this.triangles = newTrianglesVector;
  72181. }
  72182. for (i = 0; i < this.vertices.length; ++i) {
  72183. this.vertices[i].triangleCount = 0;
  72184. this.vertices[i].triangleStart = 0;
  72185. }
  72186. var t;
  72187. var j;
  72188. var v;
  72189. for (i = 0; i < this.triangles.length; ++i) {
  72190. t = this.triangles[i];
  72191. for (j = 0; j < 3; ++j) {
  72192. v = t.vertices[j];
  72193. v.triangleCount++;
  72194. }
  72195. }
  72196. var tStart = 0;
  72197. for (i = 0; i < this.vertices.length; ++i) {
  72198. this.vertices[i].triangleStart = tStart;
  72199. tStart += this.vertices[i].triangleCount;
  72200. this.vertices[i].triangleCount = 0;
  72201. }
  72202. var newReferences = new Array(this.triangles.length * 3);
  72203. for (i = 0; i < this.triangles.length; ++i) {
  72204. t = this.triangles[i];
  72205. for (j = 0; j < 3; ++j) {
  72206. v = t.vertices[j];
  72207. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  72208. v.triangleCount++;
  72209. }
  72210. }
  72211. this.references = newReferences;
  72212. if (identifyBorders) {
  72213. this.identifyBorder();
  72214. }
  72215. };
  72216. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  72217. var x = point.x;
  72218. var y = point.y;
  72219. var z = point.z;
  72220. 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
  72221. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  72222. };
  72223. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  72224. var q = vertex1.q.add(vertex2.q);
  72225. var border = vertex1.isBorder && vertex2.isBorder;
  72226. var error = 0;
  72227. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  72228. if (qDet !== 0 && !border) {
  72229. if (!pointResult) {
  72230. pointResult = BABYLON.Vector3.Zero();
  72231. }
  72232. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  72233. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  72234. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  72235. error = this.vertexError(q, pointResult);
  72236. }
  72237. else {
  72238. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  72239. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  72240. var error1 = this.vertexError(q, vertex1.position);
  72241. var error2 = this.vertexError(q, vertex2.position);
  72242. var error3 = this.vertexError(q, p3);
  72243. error = Math.min(error1, error2, error3);
  72244. if (error === error1) {
  72245. if (pointResult) {
  72246. pointResult.copyFrom(vertex1.position);
  72247. }
  72248. }
  72249. else if (error === error2) {
  72250. if (pointResult) {
  72251. pointResult.copyFrom(vertex2.position);
  72252. }
  72253. }
  72254. else {
  72255. if (pointResult) {
  72256. pointResult.copyFrom(p3);
  72257. }
  72258. }
  72259. }
  72260. return error;
  72261. };
  72262. return QuadraticErrorSimplification;
  72263. }());
  72264. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  72265. })(BABYLON || (BABYLON = {}));
  72266. //# sourceMappingURL=babylon.meshSimplification.js.map
  72267. var BABYLON;
  72268. (function (BABYLON) {
  72269. var Internals;
  72270. (function (Internals) {
  72271. var MeshLODLevel = /** @class */ (function () {
  72272. function MeshLODLevel(distance, mesh) {
  72273. this.distance = distance;
  72274. this.mesh = mesh;
  72275. }
  72276. return MeshLODLevel;
  72277. }());
  72278. Internals.MeshLODLevel = MeshLODLevel;
  72279. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  72280. })(BABYLON || (BABYLON = {}));
  72281. //# sourceMappingURL=babylon.meshLODLevel.js.map
  72282. var BABYLON;
  72283. (function (BABYLON) {
  72284. // Standard optimizations
  72285. var SceneOptimization = /** @class */ (function () {
  72286. function SceneOptimization(priority) {
  72287. if (priority === void 0) { priority = 0; }
  72288. this.priority = priority;
  72289. this.apply = function (scene) {
  72290. return true; // Return true if everything that can be done was applied
  72291. };
  72292. }
  72293. return SceneOptimization;
  72294. }());
  72295. BABYLON.SceneOptimization = SceneOptimization;
  72296. var TextureOptimization = /** @class */ (function (_super) {
  72297. __extends(TextureOptimization, _super);
  72298. function TextureOptimization(priority, maximumSize) {
  72299. if (priority === void 0) { priority = 0; }
  72300. if (maximumSize === void 0) { maximumSize = 1024; }
  72301. var _this = _super.call(this, priority) || this;
  72302. _this.priority = priority;
  72303. _this.maximumSize = maximumSize;
  72304. _this.apply = function (scene) {
  72305. var allDone = true;
  72306. for (var index = 0; index < scene.textures.length; index++) {
  72307. var texture = scene.textures[index];
  72308. if (!texture.canRescale || texture.getContext) {
  72309. continue;
  72310. }
  72311. var currentSize = texture.getSize();
  72312. var maxDimension = Math.max(currentSize.width, currentSize.height);
  72313. if (maxDimension > _this.maximumSize) {
  72314. texture.scale(0.5);
  72315. allDone = false;
  72316. }
  72317. }
  72318. return allDone;
  72319. };
  72320. return _this;
  72321. }
  72322. return TextureOptimization;
  72323. }(SceneOptimization));
  72324. BABYLON.TextureOptimization = TextureOptimization;
  72325. var HardwareScalingOptimization = /** @class */ (function (_super) {
  72326. __extends(HardwareScalingOptimization, _super);
  72327. function HardwareScalingOptimization(priority, maximumScale) {
  72328. if (priority === void 0) { priority = 0; }
  72329. if (maximumScale === void 0) { maximumScale = 2; }
  72330. var _this = _super.call(this, priority) || this;
  72331. _this.priority = priority;
  72332. _this.maximumScale = maximumScale;
  72333. _this._currentScale = 1;
  72334. _this.apply = function (scene) {
  72335. _this._currentScale++;
  72336. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  72337. return _this._currentScale >= _this.maximumScale;
  72338. };
  72339. return _this;
  72340. }
  72341. return HardwareScalingOptimization;
  72342. }(SceneOptimization));
  72343. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  72344. var ShadowsOptimization = /** @class */ (function (_super) {
  72345. __extends(ShadowsOptimization, _super);
  72346. function ShadowsOptimization() {
  72347. var _this = _super !== null && _super.apply(this, arguments) || this;
  72348. _this.apply = function (scene) {
  72349. scene.shadowsEnabled = false;
  72350. return true;
  72351. };
  72352. return _this;
  72353. }
  72354. return ShadowsOptimization;
  72355. }(SceneOptimization));
  72356. BABYLON.ShadowsOptimization = ShadowsOptimization;
  72357. var PostProcessesOptimization = /** @class */ (function (_super) {
  72358. __extends(PostProcessesOptimization, _super);
  72359. function PostProcessesOptimization() {
  72360. var _this = _super !== null && _super.apply(this, arguments) || this;
  72361. _this.apply = function (scene) {
  72362. scene.postProcessesEnabled = false;
  72363. return true;
  72364. };
  72365. return _this;
  72366. }
  72367. return PostProcessesOptimization;
  72368. }(SceneOptimization));
  72369. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  72370. var LensFlaresOptimization = /** @class */ (function (_super) {
  72371. __extends(LensFlaresOptimization, _super);
  72372. function LensFlaresOptimization() {
  72373. var _this = _super !== null && _super.apply(this, arguments) || this;
  72374. _this.apply = function (scene) {
  72375. scene.lensFlaresEnabled = false;
  72376. return true;
  72377. };
  72378. return _this;
  72379. }
  72380. return LensFlaresOptimization;
  72381. }(SceneOptimization));
  72382. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  72383. var ParticlesOptimization = /** @class */ (function (_super) {
  72384. __extends(ParticlesOptimization, _super);
  72385. function ParticlesOptimization() {
  72386. var _this = _super !== null && _super.apply(this, arguments) || this;
  72387. _this.apply = function (scene) {
  72388. scene.particlesEnabled = false;
  72389. return true;
  72390. };
  72391. return _this;
  72392. }
  72393. return ParticlesOptimization;
  72394. }(SceneOptimization));
  72395. BABYLON.ParticlesOptimization = ParticlesOptimization;
  72396. var RenderTargetsOptimization = /** @class */ (function (_super) {
  72397. __extends(RenderTargetsOptimization, _super);
  72398. function RenderTargetsOptimization() {
  72399. var _this = _super !== null && _super.apply(this, arguments) || this;
  72400. _this.apply = function (scene) {
  72401. scene.renderTargetsEnabled = false;
  72402. return true;
  72403. };
  72404. return _this;
  72405. }
  72406. return RenderTargetsOptimization;
  72407. }(SceneOptimization));
  72408. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  72409. var MergeMeshesOptimization = /** @class */ (function (_super) {
  72410. __extends(MergeMeshesOptimization, _super);
  72411. function MergeMeshesOptimization() {
  72412. var _this = _super !== null && _super.apply(this, arguments) || this;
  72413. _this._canBeMerged = function (abstractMesh) {
  72414. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  72415. return false;
  72416. }
  72417. var mesh = abstractMesh;
  72418. if (!mesh.isVisible || !mesh.isEnabled()) {
  72419. return false;
  72420. }
  72421. if (mesh.instances.length > 0) {
  72422. return false;
  72423. }
  72424. if (mesh.skeleton || mesh.hasLODLevels) {
  72425. return false;
  72426. }
  72427. if (mesh.parent) {
  72428. return false;
  72429. }
  72430. return true;
  72431. };
  72432. _this.apply = function (scene, updateSelectionTree) {
  72433. var globalPool = scene.meshes.slice(0);
  72434. var globalLength = globalPool.length;
  72435. for (var index = 0; index < globalLength; index++) {
  72436. var currentPool = new Array();
  72437. var current = globalPool[index];
  72438. // Checks
  72439. if (!_this._canBeMerged(current)) {
  72440. continue;
  72441. }
  72442. currentPool.push(current);
  72443. // Find compatible meshes
  72444. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  72445. var otherMesh = globalPool[subIndex];
  72446. if (!_this._canBeMerged(otherMesh)) {
  72447. continue;
  72448. }
  72449. if (otherMesh.material !== current.material) {
  72450. continue;
  72451. }
  72452. if (otherMesh.checkCollisions !== current.checkCollisions) {
  72453. continue;
  72454. }
  72455. currentPool.push(otherMesh);
  72456. globalLength--;
  72457. globalPool.splice(subIndex, 1);
  72458. subIndex--;
  72459. }
  72460. if (currentPool.length < 2) {
  72461. continue;
  72462. }
  72463. // Merge meshes
  72464. BABYLON.Mesh.MergeMeshes(currentPool);
  72465. }
  72466. if (updateSelectionTree != undefined) {
  72467. if (updateSelectionTree) {
  72468. scene.createOrUpdateSelectionOctree();
  72469. }
  72470. }
  72471. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  72472. scene.createOrUpdateSelectionOctree();
  72473. }
  72474. return true;
  72475. };
  72476. return _this;
  72477. }
  72478. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  72479. get: function () {
  72480. return MergeMeshesOptimization._UpdateSelectionTree;
  72481. },
  72482. set: function (value) {
  72483. MergeMeshesOptimization._UpdateSelectionTree = value;
  72484. },
  72485. enumerable: true,
  72486. configurable: true
  72487. });
  72488. MergeMeshesOptimization._UpdateSelectionTree = false;
  72489. return MergeMeshesOptimization;
  72490. }(SceneOptimization));
  72491. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  72492. // Options
  72493. var SceneOptimizerOptions = /** @class */ (function () {
  72494. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  72495. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  72496. if (trackerDuration === void 0) { trackerDuration = 2000; }
  72497. this.targetFrameRate = targetFrameRate;
  72498. this.trackerDuration = trackerDuration;
  72499. this.optimizations = new Array();
  72500. }
  72501. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  72502. var result = new SceneOptimizerOptions(targetFrameRate);
  72503. var priority = 0;
  72504. result.optimizations.push(new MergeMeshesOptimization(priority));
  72505. result.optimizations.push(new ShadowsOptimization(priority));
  72506. result.optimizations.push(new LensFlaresOptimization(priority));
  72507. // Next priority
  72508. priority++;
  72509. result.optimizations.push(new PostProcessesOptimization(priority));
  72510. result.optimizations.push(new ParticlesOptimization(priority));
  72511. // Next priority
  72512. priority++;
  72513. result.optimizations.push(new TextureOptimization(priority, 1024));
  72514. return result;
  72515. };
  72516. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  72517. var result = new SceneOptimizerOptions(targetFrameRate);
  72518. var priority = 0;
  72519. result.optimizations.push(new MergeMeshesOptimization(priority));
  72520. result.optimizations.push(new ShadowsOptimization(priority));
  72521. result.optimizations.push(new LensFlaresOptimization(priority));
  72522. // Next priority
  72523. priority++;
  72524. result.optimizations.push(new PostProcessesOptimization(priority));
  72525. result.optimizations.push(new ParticlesOptimization(priority));
  72526. // Next priority
  72527. priority++;
  72528. result.optimizations.push(new TextureOptimization(priority, 512));
  72529. // Next priority
  72530. priority++;
  72531. result.optimizations.push(new RenderTargetsOptimization(priority));
  72532. // Next priority
  72533. priority++;
  72534. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  72535. return result;
  72536. };
  72537. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  72538. var result = new SceneOptimizerOptions(targetFrameRate);
  72539. var priority = 0;
  72540. result.optimizations.push(new MergeMeshesOptimization(priority));
  72541. result.optimizations.push(new ShadowsOptimization(priority));
  72542. result.optimizations.push(new LensFlaresOptimization(priority));
  72543. // Next priority
  72544. priority++;
  72545. result.optimizations.push(new PostProcessesOptimization(priority));
  72546. result.optimizations.push(new ParticlesOptimization(priority));
  72547. // Next priority
  72548. priority++;
  72549. result.optimizations.push(new TextureOptimization(priority, 256));
  72550. // Next priority
  72551. priority++;
  72552. result.optimizations.push(new RenderTargetsOptimization(priority));
  72553. // Next priority
  72554. priority++;
  72555. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  72556. return result;
  72557. };
  72558. return SceneOptimizerOptions;
  72559. }());
  72560. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  72561. // Scene optimizer tool
  72562. var SceneOptimizer = /** @class */ (function () {
  72563. function SceneOptimizer() {
  72564. }
  72565. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  72566. // TODO: add an epsilon
  72567. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  72568. if (onSuccess) {
  72569. onSuccess();
  72570. }
  72571. return;
  72572. }
  72573. // Apply current level of optimizations
  72574. var allDone = true;
  72575. var noOptimizationApplied = true;
  72576. for (var index = 0; index < options.optimizations.length; index++) {
  72577. var optimization = options.optimizations[index];
  72578. if (optimization.priority === currentPriorityLevel) {
  72579. noOptimizationApplied = false;
  72580. allDone = allDone && optimization.apply(scene);
  72581. }
  72582. }
  72583. // If no optimization was applied, this is a failure :(
  72584. if (noOptimizationApplied) {
  72585. if (onFailure) {
  72586. onFailure();
  72587. }
  72588. return;
  72589. }
  72590. // If all optimizations were done, move to next level
  72591. if (allDone) {
  72592. currentPriorityLevel++;
  72593. }
  72594. // Let's the system running for a specific amount of time before checking FPS
  72595. scene.executeWhenReady(function () {
  72596. setTimeout(function () {
  72597. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  72598. }, options.trackerDuration);
  72599. });
  72600. };
  72601. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  72602. if (!options) {
  72603. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  72604. }
  72605. // Let's the system running for a specific amount of time before checking FPS
  72606. scene.executeWhenReady(function () {
  72607. setTimeout(function () {
  72608. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  72609. }, options.trackerDuration);
  72610. });
  72611. };
  72612. return SceneOptimizer;
  72613. }());
  72614. BABYLON.SceneOptimizer = SceneOptimizer;
  72615. })(BABYLON || (BABYLON = {}));
  72616. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  72617. var BABYLON;
  72618. (function (BABYLON) {
  72619. var OutlineRenderer = /** @class */ (function () {
  72620. function OutlineRenderer(scene) {
  72621. this.zOffset = 1;
  72622. this._scene = scene;
  72623. }
  72624. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  72625. var _this = this;
  72626. if (useOverlay === void 0) { useOverlay = false; }
  72627. var scene = this._scene;
  72628. var engine = this._scene.getEngine();
  72629. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  72630. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  72631. return;
  72632. }
  72633. var mesh = subMesh.getRenderingMesh();
  72634. var material = subMesh.getMaterial();
  72635. if (!material || !scene.activeCamera) {
  72636. return;
  72637. }
  72638. engine.enableEffect(this._effect);
  72639. // Logarithmic depth
  72640. if (material.useLogarithmicDepth) {
  72641. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  72642. }
  72643. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  72644. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  72645. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  72646. // Bones
  72647. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72648. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72649. }
  72650. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  72651. // Alpha test
  72652. if (material && material.needAlphaTesting()) {
  72653. var alphaTexture = material.getAlphaTestTexture();
  72654. if (alphaTexture) {
  72655. this._effect.setTexture("diffuseSampler", alphaTexture);
  72656. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72657. }
  72658. }
  72659. engine.setZOffset(-this.zOffset);
  72660. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  72661. engine.setZOffset(0);
  72662. };
  72663. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  72664. var defines = [];
  72665. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  72666. var mesh = subMesh.getMesh();
  72667. var material = subMesh.getMaterial();
  72668. if (material) {
  72669. // Alpha test
  72670. if (material.needAlphaTesting()) {
  72671. defines.push("#define ALPHATEST");
  72672. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72673. attribs.push(BABYLON.VertexBuffer.UVKind);
  72674. defines.push("#define UV1");
  72675. }
  72676. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72677. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72678. defines.push("#define UV2");
  72679. }
  72680. }
  72681. //Logarithmic depth
  72682. if (material.useLogarithmicDepth) {
  72683. defines.push("#define LOGARITHMICDEPTH");
  72684. }
  72685. }
  72686. // Bones
  72687. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72688. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72689. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72690. if (mesh.numBoneInfluencers > 4) {
  72691. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72692. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72693. }
  72694. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72695. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  72696. }
  72697. else {
  72698. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72699. }
  72700. // Instances
  72701. if (useInstances) {
  72702. defines.push("#define INSTANCES");
  72703. attribs.push("world0");
  72704. attribs.push("world1");
  72705. attribs.push("world2");
  72706. attribs.push("world3");
  72707. }
  72708. // Get correct effect
  72709. var join = defines.join("\n");
  72710. if (this._cachedDefines !== join) {
  72711. this._cachedDefines = join;
  72712. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  72713. }
  72714. return this._effect.isReady();
  72715. };
  72716. return OutlineRenderer;
  72717. }());
  72718. BABYLON.OutlineRenderer = OutlineRenderer;
  72719. })(BABYLON || (BABYLON = {}));
  72720. //# sourceMappingURL=babylon.outlineRenderer.js.map
  72721. var BABYLON;
  72722. (function (BABYLON) {
  72723. var FaceAdjacencies = /** @class */ (function () {
  72724. function FaceAdjacencies() {
  72725. this.edges = new Array();
  72726. this.edgesConnectedCount = 0;
  72727. }
  72728. return FaceAdjacencies;
  72729. }());
  72730. var EdgesRenderer = /** @class */ (function () {
  72731. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  72732. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  72733. if (epsilon === void 0) { epsilon = 0.95; }
  72734. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  72735. this.edgesWidthScalerForOrthographic = 1000.0;
  72736. this.edgesWidthScalerForPerspective = 50.0;
  72737. this._linesPositions = new Array();
  72738. this._linesNormals = new Array();
  72739. this._linesIndices = new Array();
  72740. this._buffers = {};
  72741. this._checkVerticesInsteadOfIndices = false;
  72742. this._source = source;
  72743. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  72744. this._epsilon = epsilon;
  72745. this._prepareRessources();
  72746. this._generateEdgesLines();
  72747. }
  72748. EdgesRenderer.prototype._prepareRessources = function () {
  72749. if (this._lineShader) {
  72750. return;
  72751. }
  72752. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  72753. attributes: ["position", "normal"],
  72754. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  72755. });
  72756. this._lineShader.disableDepthWrite = true;
  72757. this._lineShader.backFaceCulling = false;
  72758. };
  72759. EdgesRenderer.prototype._rebuild = function () {
  72760. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  72761. if (buffer) {
  72762. buffer._rebuild();
  72763. }
  72764. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  72765. if (buffer) {
  72766. buffer._rebuild();
  72767. }
  72768. var scene = this._source.getScene();
  72769. var engine = scene.getEngine();
  72770. this._ib = engine.createIndexBuffer(this._linesIndices);
  72771. };
  72772. EdgesRenderer.prototype.dispose = function () {
  72773. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  72774. if (buffer) {
  72775. buffer.dispose();
  72776. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  72777. }
  72778. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  72779. if (buffer) {
  72780. buffer.dispose();
  72781. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  72782. }
  72783. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  72784. this._lineShader.dispose();
  72785. };
  72786. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  72787. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  72788. return 0;
  72789. }
  72790. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  72791. return 1;
  72792. }
  72793. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  72794. return 2;
  72795. }
  72796. return -1;
  72797. };
  72798. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  72799. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  72800. return 0;
  72801. }
  72802. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  72803. return 1;
  72804. }
  72805. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  72806. return 2;
  72807. }
  72808. return -1;
  72809. };
  72810. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  72811. var needToCreateLine;
  72812. if (edge === undefined) {
  72813. needToCreateLine = true;
  72814. }
  72815. else {
  72816. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  72817. needToCreateLine = dotProduct < this._epsilon;
  72818. }
  72819. if (needToCreateLine) {
  72820. var offset = this._linesPositions.length / 3;
  72821. var normal = p0.subtract(p1);
  72822. normal.normalize();
  72823. // Positions
  72824. this._linesPositions.push(p0.x);
  72825. this._linesPositions.push(p0.y);
  72826. this._linesPositions.push(p0.z);
  72827. this._linesPositions.push(p0.x);
  72828. this._linesPositions.push(p0.y);
  72829. this._linesPositions.push(p0.z);
  72830. this._linesPositions.push(p1.x);
  72831. this._linesPositions.push(p1.y);
  72832. this._linesPositions.push(p1.z);
  72833. this._linesPositions.push(p1.x);
  72834. this._linesPositions.push(p1.y);
  72835. this._linesPositions.push(p1.z);
  72836. // Normals
  72837. this._linesNormals.push(p1.x);
  72838. this._linesNormals.push(p1.y);
  72839. this._linesNormals.push(p1.z);
  72840. this._linesNormals.push(-1);
  72841. this._linesNormals.push(p1.x);
  72842. this._linesNormals.push(p1.y);
  72843. this._linesNormals.push(p1.z);
  72844. this._linesNormals.push(1);
  72845. this._linesNormals.push(p0.x);
  72846. this._linesNormals.push(p0.y);
  72847. this._linesNormals.push(p0.z);
  72848. this._linesNormals.push(-1);
  72849. this._linesNormals.push(p0.x);
  72850. this._linesNormals.push(p0.y);
  72851. this._linesNormals.push(p0.z);
  72852. this._linesNormals.push(1);
  72853. // Indices
  72854. this._linesIndices.push(offset);
  72855. this._linesIndices.push(offset + 1);
  72856. this._linesIndices.push(offset + 2);
  72857. this._linesIndices.push(offset);
  72858. this._linesIndices.push(offset + 2);
  72859. this._linesIndices.push(offset + 3);
  72860. }
  72861. };
  72862. EdgesRenderer.prototype._generateEdgesLines = function () {
  72863. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  72864. var indices = this._source.getIndices();
  72865. if (!indices || !positions) {
  72866. return;
  72867. }
  72868. // First let's find adjacencies
  72869. var adjacencies = new Array();
  72870. var faceNormals = new Array();
  72871. var index;
  72872. var faceAdjacencies;
  72873. // Prepare faces
  72874. for (index = 0; index < indices.length; index += 3) {
  72875. faceAdjacencies = new FaceAdjacencies();
  72876. var p0Index = indices[index];
  72877. var p1Index = indices[index + 1];
  72878. var p2Index = indices[index + 2];
  72879. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  72880. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  72881. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  72882. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  72883. faceNormal.normalize();
  72884. faceNormals.push(faceNormal);
  72885. adjacencies.push(faceAdjacencies);
  72886. }
  72887. // Scan
  72888. for (index = 0; index < adjacencies.length; index++) {
  72889. faceAdjacencies = adjacencies[index];
  72890. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  72891. var otherFaceAdjacencies = adjacencies[otherIndex];
  72892. if (faceAdjacencies.edgesConnectedCount === 3) {
  72893. break;
  72894. }
  72895. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  72896. continue;
  72897. }
  72898. var otherP0 = indices[otherIndex * 3];
  72899. var otherP1 = indices[otherIndex * 3 + 1];
  72900. var otherP2 = indices[otherIndex * 3 + 2];
  72901. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  72902. var otherEdgeIndex = 0;
  72903. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  72904. continue;
  72905. }
  72906. switch (edgeIndex) {
  72907. case 0:
  72908. if (this._checkVerticesInsteadOfIndices) {
  72909. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  72910. }
  72911. else {
  72912. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  72913. }
  72914. break;
  72915. case 1:
  72916. if (this._checkVerticesInsteadOfIndices) {
  72917. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  72918. }
  72919. else {
  72920. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  72921. }
  72922. break;
  72923. case 2:
  72924. if (this._checkVerticesInsteadOfIndices) {
  72925. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  72926. }
  72927. else {
  72928. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  72929. }
  72930. break;
  72931. }
  72932. if (otherEdgeIndex === -1) {
  72933. continue;
  72934. }
  72935. faceAdjacencies.edges[edgeIndex] = otherIndex;
  72936. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  72937. faceAdjacencies.edgesConnectedCount++;
  72938. otherFaceAdjacencies.edgesConnectedCount++;
  72939. if (faceAdjacencies.edgesConnectedCount === 3) {
  72940. break;
  72941. }
  72942. }
  72943. }
  72944. }
  72945. // Create lines
  72946. for (index = 0; index < adjacencies.length; index++) {
  72947. // 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
  72948. var current = adjacencies[index];
  72949. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  72950. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  72951. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  72952. }
  72953. // Merge into a single mesh
  72954. var engine = this._source.getScene().getEngine();
  72955. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  72956. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  72957. this._ib = engine.createIndexBuffer(this._linesIndices);
  72958. this._indicesCount = this._linesIndices.length;
  72959. };
  72960. EdgesRenderer.prototype.render = function () {
  72961. var scene = this._source.getScene();
  72962. if (!this._lineShader.isReady() || !scene.activeCamera) {
  72963. return;
  72964. }
  72965. var engine = scene.getEngine();
  72966. this._lineShader._preBind();
  72967. // VBOs
  72968. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  72969. scene.resetCachedMaterial();
  72970. this._lineShader.setColor4("color", this._source.edgesColor);
  72971. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  72972. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  72973. }
  72974. else {
  72975. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  72976. }
  72977. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  72978. this._lineShader.bind(this._source.getWorldMatrix());
  72979. // Draw order
  72980. engine.draw(true, 0, this._indicesCount);
  72981. this._lineShader.unbind();
  72982. engine.setDepthWrite(true);
  72983. };
  72984. return EdgesRenderer;
  72985. }());
  72986. BABYLON.EdgesRenderer = EdgesRenderer;
  72987. })(BABYLON || (BABYLON = {}));
  72988. //# sourceMappingURL=babylon.edgesRenderer.js.map
  72989. var BABYLON;
  72990. (function (BABYLON) {
  72991. /**
  72992. * Special Glow Blur post process only blurring the alpha channel
  72993. * It enforces keeping the most luminous color in the color channel.
  72994. */
  72995. var GlowBlurPostProcess = /** @class */ (function (_super) {
  72996. __extends(GlowBlurPostProcess, _super);
  72997. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  72998. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  72999. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  73000. _this.direction = direction;
  73001. _this.kernel = kernel;
  73002. _this.onApplyObservable.add(function (effect) {
  73003. effect.setFloat2("screenSize", _this.width, _this.height);
  73004. effect.setVector2("direction", _this.direction);
  73005. effect.setFloat("blurWidth", _this.kernel);
  73006. });
  73007. return _this;
  73008. }
  73009. return GlowBlurPostProcess;
  73010. }(BABYLON.PostProcess));
  73011. /**
  73012. * The highlight layer Helps adding a glow effect around a mesh.
  73013. *
  73014. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  73015. * glowy meshes to your scene.
  73016. *
  73017. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  73018. */
  73019. var HighlightLayer = /** @class */ (function () {
  73020. /**
  73021. * Instantiates a new highlight Layer and references it to the scene..
  73022. * @param name The name of the layer
  73023. * @param scene The scene to use the layer in
  73024. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  73025. */
  73026. function HighlightLayer(name, scene, options) {
  73027. this.name = name;
  73028. this._vertexBuffers = {};
  73029. this._mainTextureDesiredSize = { width: 0, height: 0 };
  73030. this._meshes = {};
  73031. this._maxSize = 0;
  73032. this._shouldRender = false;
  73033. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  73034. this._excludedMeshes = {};
  73035. /**
  73036. * Specifies whether or not the inner glow is ACTIVE in the layer.
  73037. */
  73038. this.innerGlow = true;
  73039. /**
  73040. * Specifies whether or not the outer glow is ACTIVE in the layer.
  73041. */
  73042. this.outerGlow = true;
  73043. /**
  73044. * Specifies wether the highlight layer is enabled or not.
  73045. */
  73046. this.isEnabled = true;
  73047. /**
  73048. * An event triggered when the highlight layer has been disposed.
  73049. * @type {BABYLON.Observable}
  73050. */
  73051. this.onDisposeObservable = new BABYLON.Observable();
  73052. /**
  73053. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  73054. * @type {BABYLON.Observable}
  73055. */
  73056. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  73057. /**
  73058. * An event triggered when the highlight layer is being blurred.
  73059. * @type {BABYLON.Observable}
  73060. */
  73061. this.onBeforeBlurObservable = new BABYLON.Observable();
  73062. /**
  73063. * An event triggered when the highlight layer has been blurred.
  73064. * @type {BABYLON.Observable}
  73065. */
  73066. this.onAfterBlurObservable = new BABYLON.Observable();
  73067. /**
  73068. * An event triggered when the glowing blurred texture is being merged in the scene.
  73069. * @type {BABYLON.Observable}
  73070. */
  73071. this.onBeforeComposeObservable = new BABYLON.Observable();
  73072. /**
  73073. * An event triggered when the glowing blurred texture has been merged in the scene.
  73074. * @type {BABYLON.Observable}
  73075. */
  73076. this.onAfterComposeObservable = new BABYLON.Observable();
  73077. /**
  73078. * An event triggered when the highlight layer changes its size.
  73079. * @type {BABYLON.Observable}
  73080. */
  73081. this.onSizeChangedObservable = new BABYLON.Observable();
  73082. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  73083. var engine = scene.getEngine();
  73084. this._engine = engine;
  73085. this._maxSize = this._engine.getCaps().maxTextureSize;
  73086. this._scene.highlightLayers.push(this);
  73087. // Warn on stencil.
  73088. if (!this._engine.isStencilEnable) {
  73089. 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 }");
  73090. }
  73091. // Adapt options
  73092. this._options = options || {
  73093. mainTextureRatio: 0.5,
  73094. blurTextureSizeRatio: 0.5,
  73095. blurHorizontalSize: 1.0,
  73096. blurVerticalSize: 1.0,
  73097. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  73098. camera: null
  73099. };
  73100. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  73101. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  73102. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  73103. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  73104. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  73105. // VBO
  73106. var vertices = [];
  73107. vertices.push(1, 1);
  73108. vertices.push(-1, 1);
  73109. vertices.push(-1, -1);
  73110. vertices.push(1, -1);
  73111. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  73112. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  73113. this._createIndexBuffer();
  73114. // Effect
  73115. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  73116. // Render target
  73117. this.setMainTextureSize();
  73118. // Create Textures and post processes
  73119. this.createTextureAndPostProcesses();
  73120. }
  73121. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  73122. /**
  73123. * Gets the horizontal size of the blur.
  73124. */
  73125. get: function () {
  73126. return this._horizontalBlurPostprocess.kernel;
  73127. },
  73128. /**
  73129. * Specifies the horizontal size of the blur.
  73130. */
  73131. set: function (value) {
  73132. this._horizontalBlurPostprocess.kernel = value;
  73133. },
  73134. enumerable: true,
  73135. configurable: true
  73136. });
  73137. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  73138. /**
  73139. * Gets the vertical size of the blur.
  73140. */
  73141. get: function () {
  73142. return this._verticalBlurPostprocess.kernel;
  73143. },
  73144. /**
  73145. * Specifies the vertical size of the blur.
  73146. */
  73147. set: function (value) {
  73148. this._verticalBlurPostprocess.kernel = value;
  73149. },
  73150. enumerable: true,
  73151. configurable: true
  73152. });
  73153. Object.defineProperty(HighlightLayer.prototype, "camera", {
  73154. /**
  73155. * Gets the camera attached to the layer.
  73156. */
  73157. get: function () {
  73158. return this._options.camera;
  73159. },
  73160. enumerable: true,
  73161. configurable: true
  73162. });
  73163. HighlightLayer.prototype._createIndexBuffer = function () {
  73164. var engine = this._scene.getEngine();
  73165. // Indices
  73166. var indices = [];
  73167. indices.push(0);
  73168. indices.push(1);
  73169. indices.push(2);
  73170. indices.push(0);
  73171. indices.push(2);
  73172. indices.push(3);
  73173. this._indexBuffer = engine.createIndexBuffer(indices);
  73174. };
  73175. HighlightLayer.prototype._rebuild = function () {
  73176. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73177. if (vb) {
  73178. vb._rebuild();
  73179. }
  73180. this._createIndexBuffer();
  73181. };
  73182. /**
  73183. * Creates the render target textures and post processes used in the highlight layer.
  73184. */
  73185. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  73186. var _this = this;
  73187. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  73188. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  73189. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  73190. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  73191. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  73192. width: this._mainTextureDesiredSize.width,
  73193. height: this._mainTextureDesiredSize.height
  73194. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  73195. this._mainTexture.activeCamera = this._options.camera;
  73196. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73197. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73198. this._mainTexture.anisotropicFilteringLevel = 1;
  73199. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73200. this._mainTexture.renderParticles = false;
  73201. this._mainTexture.renderList = null;
  73202. this._mainTexture.ignoreCameraViewport = true;
  73203. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  73204. width: blurTextureWidth,
  73205. height: blurTextureHeight
  73206. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  73207. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73208. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73209. this._blurTexture.anisotropicFilteringLevel = 16;
  73210. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73211. this._blurTexture.renderParticles = false;
  73212. this._blurTexture.ignoreCameraViewport = true;
  73213. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  73214. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  73215. effect.setTexture("textureSampler", _this._mainTexture);
  73216. });
  73217. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  73218. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  73219. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  73220. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  73221. });
  73222. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  73223. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  73224. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  73225. });
  73226. }
  73227. else {
  73228. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  73229. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  73230. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  73231. });
  73232. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  73233. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  73234. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  73235. });
  73236. }
  73237. this._mainTexture.onAfterUnbindObservable.add(function () {
  73238. _this.onBeforeBlurObservable.notifyObservers(_this);
  73239. var internalTexture = _this._blurTexture.getInternalTexture();
  73240. if (internalTexture) {
  73241. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  73242. }
  73243. _this.onAfterBlurObservable.notifyObservers(_this);
  73244. });
  73245. // Custom render function
  73246. var renderSubMesh = function (subMesh) {
  73247. if (!_this._meshes) {
  73248. return;
  73249. }
  73250. var material = subMesh.getMaterial();
  73251. var mesh = subMesh.getRenderingMesh();
  73252. var scene = _this._scene;
  73253. var engine = scene.getEngine();
  73254. if (!material) {
  73255. return;
  73256. }
  73257. // Culling
  73258. engine.setState(material.backFaceCulling);
  73259. // Managing instances
  73260. var batch = mesh._getInstancesRenderList(subMesh._id);
  73261. if (batch.mustReturn) {
  73262. return;
  73263. }
  73264. // Excluded Mesh
  73265. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  73266. return;
  73267. }
  73268. ;
  73269. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  73270. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  73271. var emissiveTexture = null;
  73272. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  73273. emissiveTexture = material.emissiveTexture;
  73274. }
  73275. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  73276. engine.enableEffect(_this._glowMapGenerationEffect);
  73277. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  73278. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  73279. if (highlightLayerMesh) {
  73280. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  73281. }
  73282. else {
  73283. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  73284. }
  73285. // Alpha test
  73286. if (material && material.needAlphaTesting()) {
  73287. var alphaTexture = material.getAlphaTestTexture();
  73288. if (alphaTexture) {
  73289. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  73290. var textureMatrix = alphaTexture.getTextureMatrix();
  73291. if (textureMatrix) {
  73292. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  73293. }
  73294. }
  73295. }
  73296. // Glow emissive only
  73297. if (emissiveTexture) {
  73298. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  73299. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  73300. }
  73301. // Bones
  73302. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73303. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73304. }
  73305. // Draw
  73306. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  73307. }
  73308. else {
  73309. // Need to reset refresh rate of the shadowMap
  73310. _this._mainTexture.resetRefreshCounter();
  73311. }
  73312. };
  73313. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73314. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  73315. var index;
  73316. var engine = _this._scene.getEngine();
  73317. if (depthOnlySubMeshes.length) {
  73318. engine.setColorWrite(false);
  73319. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73320. renderSubMesh(depthOnlySubMeshes.data[index]);
  73321. }
  73322. engine.setColorWrite(true);
  73323. }
  73324. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73325. renderSubMesh(opaqueSubMeshes.data[index]);
  73326. }
  73327. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73328. renderSubMesh(alphaTestSubMeshes.data[index]);
  73329. }
  73330. for (index = 0; index < transparentSubMeshes.length; index++) {
  73331. renderSubMesh(transparentSubMeshes.data[index]);
  73332. }
  73333. };
  73334. this._mainTexture.onClearObservable.add(function (engine) {
  73335. engine.clear(HighlightLayer.neutralColor, true, true, true);
  73336. });
  73337. };
  73338. /**
  73339. * Checks for the readiness of the element composing the layer.
  73340. * @param subMesh the mesh to check for
  73341. * @param useInstances specify wether or not to use instances to render the mesh
  73342. * @param emissiveTexture the associated emissive texture used to generate the glow
  73343. * @return true if ready otherwise, false
  73344. */
  73345. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  73346. var material = subMesh.getMaterial();
  73347. if (!material) {
  73348. return false;
  73349. }
  73350. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  73351. return false;
  73352. }
  73353. var defines = [];
  73354. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73355. var mesh = subMesh.getMesh();
  73356. var uv1 = false;
  73357. var uv2 = false;
  73358. // Alpha test
  73359. if (material && material.needAlphaTesting()) {
  73360. var alphaTexture = material.getAlphaTestTexture();
  73361. if (alphaTexture) {
  73362. defines.push("#define ALPHATEST");
  73363. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  73364. alphaTexture.coordinatesIndex === 1) {
  73365. defines.push("#define DIFFUSEUV2");
  73366. uv2 = true;
  73367. }
  73368. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73369. defines.push("#define DIFFUSEUV1");
  73370. uv1 = true;
  73371. }
  73372. }
  73373. }
  73374. // Emissive
  73375. if (emissiveTexture) {
  73376. defines.push("#define EMISSIVE");
  73377. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  73378. emissiveTexture.coordinatesIndex === 1) {
  73379. defines.push("#define EMISSIVEUV2");
  73380. uv2 = true;
  73381. }
  73382. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73383. defines.push("#define EMISSIVEUV1");
  73384. uv1 = true;
  73385. }
  73386. }
  73387. if (uv1) {
  73388. attribs.push(BABYLON.VertexBuffer.UVKind);
  73389. defines.push("#define UV1");
  73390. }
  73391. if (uv2) {
  73392. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73393. defines.push("#define UV2");
  73394. }
  73395. // Bones
  73396. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73397. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73398. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73399. if (mesh.numBoneInfluencers > 4) {
  73400. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73401. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73402. }
  73403. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73404. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  73405. }
  73406. else {
  73407. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73408. }
  73409. // Instances
  73410. if (useInstances) {
  73411. defines.push("#define INSTANCES");
  73412. attribs.push("world0");
  73413. attribs.push("world1");
  73414. attribs.push("world2");
  73415. attribs.push("world3");
  73416. }
  73417. // Get correct effect
  73418. var join = defines.join("\n");
  73419. if (this._cachedDefines !== join) {
  73420. this._cachedDefines = join;
  73421. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  73422. }
  73423. return this._glowMapGenerationEffect.isReady();
  73424. };
  73425. /**
  73426. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  73427. */
  73428. HighlightLayer.prototype.render = function () {
  73429. var currentEffect = this._glowMapMergeEffect;
  73430. // Check
  73431. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  73432. return;
  73433. var engine = this._scene.getEngine();
  73434. this.onBeforeComposeObservable.notifyObservers(this);
  73435. // Render
  73436. engine.enableEffect(currentEffect);
  73437. engine.setState(false);
  73438. // Cache
  73439. var previousStencilBuffer = engine.getStencilBuffer();
  73440. var previousStencilFunction = engine.getStencilFunction();
  73441. var previousStencilMask = engine.getStencilMask();
  73442. var previousStencilOperationPass = engine.getStencilOperationPass();
  73443. var previousStencilOperationFail = engine.getStencilOperationFail();
  73444. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  73445. var previousAlphaMode = engine.getAlphaMode();
  73446. // Texture
  73447. currentEffect.setTexture("textureSampler", this._blurTexture);
  73448. // VBOs
  73449. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  73450. // Stencil operations
  73451. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  73452. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  73453. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  73454. // Draw order
  73455. engine.setAlphaMode(this._options.alphaBlendingMode);
  73456. engine.setStencilMask(0x00);
  73457. engine.setStencilBuffer(true);
  73458. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  73459. if (this.outerGlow) {
  73460. currentEffect.setFloat("offset", 0);
  73461. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  73462. engine.draw(true, 0, 6);
  73463. }
  73464. if (this.innerGlow) {
  73465. currentEffect.setFloat("offset", 1);
  73466. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  73467. engine.draw(true, 0, 6);
  73468. }
  73469. // Restore Cache
  73470. engine.setStencilFunction(previousStencilFunction);
  73471. engine.setStencilMask(previousStencilMask);
  73472. engine.setAlphaMode(previousAlphaMode);
  73473. engine.setStencilBuffer(previousStencilBuffer);
  73474. engine.setStencilOperationPass(previousStencilOperationPass);
  73475. engine.setStencilOperationFail(previousStencilOperationFail);
  73476. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  73477. engine._stencilState.reset();
  73478. this.onAfterComposeObservable.notifyObservers(this);
  73479. // Handle size changes.
  73480. var size = this._mainTexture.getSize();
  73481. this.setMainTextureSize();
  73482. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  73483. // Recreate RTT and post processes on size change.
  73484. this.onSizeChangedObservable.notifyObservers(this);
  73485. this.disposeTextureAndPostProcesses();
  73486. this.createTextureAndPostProcesses();
  73487. }
  73488. };
  73489. /**
  73490. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  73491. * @param mesh The mesh to exclude from the highlight layer
  73492. */
  73493. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  73494. if (!this._excludedMeshes) {
  73495. return;
  73496. }
  73497. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  73498. if (!meshExcluded) {
  73499. this._excludedMeshes[mesh.uniqueId] = {
  73500. mesh: mesh,
  73501. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  73502. mesh.getEngine().setStencilBuffer(false);
  73503. }),
  73504. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  73505. mesh.getEngine().setStencilBuffer(true);
  73506. }),
  73507. };
  73508. }
  73509. };
  73510. /**
  73511. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  73512. * @param mesh The mesh to highlight
  73513. */
  73514. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  73515. if (!this._excludedMeshes) {
  73516. return;
  73517. }
  73518. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  73519. if (meshExcluded) {
  73520. if (meshExcluded.beforeRender) {
  73521. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  73522. }
  73523. if (meshExcluded.afterRender) {
  73524. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  73525. }
  73526. }
  73527. this._excludedMeshes[mesh.uniqueId] = null;
  73528. };
  73529. /**
  73530. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  73531. * @param mesh The mesh to highlight
  73532. * @param color The color of the highlight
  73533. * @param glowEmissiveOnly Extract the glow from the emissive texture
  73534. */
  73535. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  73536. var _this = this;
  73537. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  73538. if (!this._meshes) {
  73539. return;
  73540. }
  73541. var meshHighlight = this._meshes[mesh.uniqueId];
  73542. if (meshHighlight) {
  73543. meshHighlight.color = color;
  73544. }
  73545. else {
  73546. this._meshes[mesh.uniqueId] = {
  73547. mesh: mesh,
  73548. color: color,
  73549. // Lambda required for capture due to Observable this context
  73550. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  73551. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  73552. _this.defaultStencilReference(mesh);
  73553. }
  73554. else {
  73555. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  73556. }
  73557. }),
  73558. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  73559. glowEmissiveOnly: glowEmissiveOnly
  73560. };
  73561. }
  73562. this._shouldRender = true;
  73563. };
  73564. /**
  73565. * Remove a mesh from the highlight layer in order to make it stop glowing.
  73566. * @param mesh The mesh to highlight
  73567. */
  73568. HighlightLayer.prototype.removeMesh = function (mesh) {
  73569. if (!this._meshes) {
  73570. return;
  73571. }
  73572. var meshHighlight = this._meshes[mesh.uniqueId];
  73573. if (meshHighlight) {
  73574. if (meshHighlight.observerHighlight) {
  73575. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  73576. }
  73577. if (meshHighlight.observerDefault) {
  73578. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  73579. }
  73580. }
  73581. this._meshes[mesh.uniqueId] = null;
  73582. this._shouldRender = false;
  73583. for (var meshHighlightToCheck in this._meshes) {
  73584. if (meshHighlightToCheck) {
  73585. this._shouldRender = true;
  73586. break;
  73587. }
  73588. }
  73589. };
  73590. /**
  73591. * Returns true if the layer contains information to display, otherwise false.
  73592. */
  73593. HighlightLayer.prototype.shouldRender = function () {
  73594. return this.isEnabled && this._shouldRender;
  73595. };
  73596. /**
  73597. * Sets the main texture desired size which is the closest power of two
  73598. * of the engine canvas size.
  73599. */
  73600. HighlightLayer.prototype.setMainTextureSize = function () {
  73601. if (this._options.mainTextureFixedSize) {
  73602. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  73603. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  73604. }
  73605. else {
  73606. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  73607. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  73608. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  73609. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  73610. }
  73611. };
  73612. /**
  73613. * Force the stencil to the normal expected value for none glowing parts
  73614. */
  73615. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  73616. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  73617. };
  73618. /**
  73619. * Dispose only the render target textures and post process.
  73620. */
  73621. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  73622. this._blurTexture.dispose();
  73623. this._mainTexture.dispose();
  73624. this._downSamplePostprocess.dispose();
  73625. this._horizontalBlurPostprocess.dispose();
  73626. this._verticalBlurPostprocess.dispose();
  73627. };
  73628. /**
  73629. * Dispose the highlight layer and free resources.
  73630. */
  73631. HighlightLayer.prototype.dispose = function () {
  73632. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73633. if (vertexBuffer) {
  73634. vertexBuffer.dispose();
  73635. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73636. }
  73637. if (this._indexBuffer) {
  73638. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73639. this._indexBuffer = null;
  73640. }
  73641. // Clean textures and post processes
  73642. this.disposeTextureAndPostProcesses();
  73643. if (this._meshes) {
  73644. // Clean mesh references
  73645. for (var id in this._meshes) {
  73646. var meshHighlight = this._meshes[id];
  73647. if (meshHighlight && meshHighlight.mesh) {
  73648. if (meshHighlight.observerHighlight) {
  73649. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  73650. }
  73651. if (meshHighlight.observerDefault) {
  73652. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  73653. }
  73654. }
  73655. }
  73656. this._meshes = null;
  73657. }
  73658. if (this._excludedMeshes) {
  73659. for (var id in this._excludedMeshes) {
  73660. var meshHighlight = this._excludedMeshes[id];
  73661. if (meshHighlight) {
  73662. if (meshHighlight.beforeRender) {
  73663. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  73664. }
  73665. if (meshHighlight.afterRender) {
  73666. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  73667. }
  73668. }
  73669. }
  73670. this._excludedMeshes = null;
  73671. }
  73672. // Remove from scene
  73673. var index = this._scene.highlightLayers.indexOf(this, 0);
  73674. if (index > -1) {
  73675. this._scene.highlightLayers.splice(index, 1);
  73676. }
  73677. // Callback
  73678. this.onDisposeObservable.notifyObservers(this);
  73679. this.onDisposeObservable.clear();
  73680. this.onBeforeRenderMainTextureObservable.clear();
  73681. this.onBeforeBlurObservable.clear();
  73682. this.onBeforeComposeObservable.clear();
  73683. this.onAfterComposeObservable.clear();
  73684. this.onSizeChangedObservable.clear();
  73685. };
  73686. /**
  73687. * The neutral color used during the preparation of the glow effect.
  73688. * This is black by default as the blend operation is a blend operation.
  73689. */
  73690. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  73691. /**
  73692. * Stencil value used for glowing meshes.
  73693. */
  73694. HighlightLayer.glowingMeshStencilReference = 0x02;
  73695. /**
  73696. * Stencil value used for the other meshes in the scene.
  73697. */
  73698. HighlightLayer.normalMeshStencilReference = 0x01;
  73699. return HighlightLayer;
  73700. }());
  73701. BABYLON.HighlightLayer = HighlightLayer;
  73702. })(BABYLON || (BABYLON = {}));
  73703. //# sourceMappingURL=babylon.highlightlayer.js.map
  73704. var BABYLON;
  73705. (function (BABYLON) {
  73706. var AssetTaskState;
  73707. (function (AssetTaskState) {
  73708. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  73709. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  73710. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  73711. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  73712. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  73713. var AbstractAssetTask = /** @class */ (function () {
  73714. function AbstractAssetTask(name) {
  73715. this.name = name;
  73716. this.isCompleted = false;
  73717. this.taskState = AssetTaskState.INIT;
  73718. }
  73719. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  73720. var _this = this;
  73721. this.taskState = AssetTaskState.RUNNING;
  73722. this.runTask(scene, function () {
  73723. _this.onDoneCallback(onSuccess, onError);
  73724. }, function (msg, exception) {
  73725. _this.onErrorCallback(onError, msg, exception);
  73726. });
  73727. };
  73728. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  73729. throw new Error("runTask is not implemented");
  73730. };
  73731. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  73732. this.taskState = AssetTaskState.ERROR;
  73733. this.errorObject = {
  73734. message: message,
  73735. exception: exception
  73736. };
  73737. if (this.onError) {
  73738. this.onError(this, message, exception);
  73739. }
  73740. onError();
  73741. };
  73742. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  73743. try {
  73744. this.taskState = AssetTaskState.DONE;
  73745. this.isCompleted = true;
  73746. if (this.onSuccess) {
  73747. this.onSuccess(this);
  73748. }
  73749. onSuccess();
  73750. }
  73751. catch (e) {
  73752. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  73753. }
  73754. };
  73755. return AbstractAssetTask;
  73756. }());
  73757. BABYLON.AbstractAssetTask = AbstractAssetTask;
  73758. var AssetsProgressEvent = /** @class */ (function () {
  73759. function AssetsProgressEvent(remainingCount, totalCount, task) {
  73760. this.remainingCount = remainingCount;
  73761. this.totalCount = totalCount;
  73762. this.task = task;
  73763. }
  73764. return AssetsProgressEvent;
  73765. }());
  73766. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  73767. var MeshAssetTask = /** @class */ (function (_super) {
  73768. __extends(MeshAssetTask, _super);
  73769. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  73770. var _this = _super.call(this, name) || this;
  73771. _this.name = name;
  73772. _this.meshesNames = meshesNames;
  73773. _this.rootUrl = rootUrl;
  73774. _this.sceneFilename = sceneFilename;
  73775. return _this;
  73776. }
  73777. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  73778. var _this = this;
  73779. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  73780. _this.loadedMeshes = meshes;
  73781. _this.loadedParticleSystems = particleSystems;
  73782. _this.loadedSkeletons = skeletons;
  73783. onSuccess();
  73784. }, null, function (scene, message, exception) {
  73785. onError(message, exception);
  73786. });
  73787. };
  73788. return MeshAssetTask;
  73789. }(AbstractAssetTask));
  73790. BABYLON.MeshAssetTask = MeshAssetTask;
  73791. var TextFileAssetTask = /** @class */ (function (_super) {
  73792. __extends(TextFileAssetTask, _super);
  73793. function TextFileAssetTask(name, url) {
  73794. var _this = _super.call(this, name) || this;
  73795. _this.name = name;
  73796. _this.url = url;
  73797. return _this;
  73798. }
  73799. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  73800. var _this = this;
  73801. BABYLON.Tools.LoadFile(this.url, function (data) {
  73802. _this.text = data;
  73803. onSuccess();
  73804. }, undefined, scene.database, false, function (request, exception) {
  73805. if (request) {
  73806. onError(request.status + " " + request.statusText, exception);
  73807. }
  73808. });
  73809. };
  73810. return TextFileAssetTask;
  73811. }(AbstractAssetTask));
  73812. BABYLON.TextFileAssetTask = TextFileAssetTask;
  73813. var BinaryFileAssetTask = /** @class */ (function (_super) {
  73814. __extends(BinaryFileAssetTask, _super);
  73815. function BinaryFileAssetTask(name, url) {
  73816. var _this = _super.call(this, name) || this;
  73817. _this.name = name;
  73818. _this.url = url;
  73819. return _this;
  73820. }
  73821. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  73822. var _this = this;
  73823. BABYLON.Tools.LoadFile(this.url, function (data) {
  73824. _this.data = data;
  73825. onSuccess();
  73826. }, undefined, scene.database, true, function (request, exception) {
  73827. if (request) {
  73828. onError(request.status + " " + request.statusText, exception);
  73829. }
  73830. });
  73831. };
  73832. return BinaryFileAssetTask;
  73833. }(AbstractAssetTask));
  73834. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  73835. var ImageAssetTask = /** @class */ (function (_super) {
  73836. __extends(ImageAssetTask, _super);
  73837. function ImageAssetTask(name, url) {
  73838. var _this = _super.call(this, name) || this;
  73839. _this.name = name;
  73840. _this.url = url;
  73841. return _this;
  73842. }
  73843. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  73844. var _this = this;
  73845. var img = new Image();
  73846. BABYLON.Tools.SetCorsBehavior(this.url, img);
  73847. img.onload = function () {
  73848. _this.image = img;
  73849. onSuccess();
  73850. };
  73851. img.onerror = function (err) {
  73852. onError("Error loading image", err);
  73853. };
  73854. img.src = this.url;
  73855. };
  73856. return ImageAssetTask;
  73857. }(AbstractAssetTask));
  73858. BABYLON.ImageAssetTask = ImageAssetTask;
  73859. var TextureAssetTask = /** @class */ (function (_super) {
  73860. __extends(TextureAssetTask, _super);
  73861. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  73862. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73863. var _this = _super.call(this, name) || this;
  73864. _this.name = name;
  73865. _this.url = url;
  73866. _this.noMipmap = noMipmap;
  73867. _this.invertY = invertY;
  73868. _this.samplingMode = samplingMode;
  73869. return _this;
  73870. }
  73871. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  73872. var onload = function () {
  73873. onSuccess();
  73874. };
  73875. var onerror = function (msg, exception) {
  73876. onError(msg, exception);
  73877. };
  73878. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  73879. };
  73880. return TextureAssetTask;
  73881. }(AbstractAssetTask));
  73882. BABYLON.TextureAssetTask = TextureAssetTask;
  73883. var CubeTextureAssetTask = /** @class */ (function (_super) {
  73884. __extends(CubeTextureAssetTask, _super);
  73885. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  73886. var _this = _super.call(this, name) || this;
  73887. _this.name = name;
  73888. _this.url = url;
  73889. _this.extensions = extensions;
  73890. _this.noMipmap = noMipmap;
  73891. _this.files = files;
  73892. return _this;
  73893. }
  73894. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  73895. var onload = function () {
  73896. onSuccess();
  73897. };
  73898. var onerror = function (msg, exception) {
  73899. onError(msg, exception);
  73900. };
  73901. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  73902. };
  73903. return CubeTextureAssetTask;
  73904. }(AbstractAssetTask));
  73905. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  73906. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  73907. __extends(HDRCubeTextureAssetTask, _super);
  73908. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  73909. if (noMipmap === void 0) { noMipmap = false; }
  73910. if (generateHarmonics === void 0) { generateHarmonics = true; }
  73911. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  73912. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  73913. var _this = _super.call(this, name) || this;
  73914. _this.name = name;
  73915. _this.url = url;
  73916. _this.size = size;
  73917. _this.noMipmap = noMipmap;
  73918. _this.generateHarmonics = generateHarmonics;
  73919. _this.useInGammaSpace = useInGammaSpace;
  73920. _this.usePMREMGenerator = usePMREMGenerator;
  73921. return _this;
  73922. }
  73923. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  73924. var onload = function () {
  73925. onSuccess();
  73926. };
  73927. var onerror = function (message, exception) {
  73928. onError(message, exception);
  73929. };
  73930. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  73931. };
  73932. return HDRCubeTextureAssetTask;
  73933. }(AbstractAssetTask));
  73934. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  73935. var AssetsManager = /** @class */ (function () {
  73936. function AssetsManager(scene) {
  73937. this.tasks = new Array();
  73938. this.waitingTasksCount = 0;
  73939. //Observables
  73940. this.onTaskSuccessObservable = new BABYLON.Observable();
  73941. this.onTaskErrorObservable = new BABYLON.Observable();
  73942. this.onTasksDoneObservable = new BABYLON.Observable();
  73943. this.onProgressObservable = new BABYLON.Observable();
  73944. this.useDefaultLoadingScreen = true;
  73945. this._scene = scene;
  73946. }
  73947. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  73948. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  73949. this.tasks.push(task);
  73950. return task;
  73951. };
  73952. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  73953. var task = new TextFileAssetTask(taskName, url);
  73954. this.tasks.push(task);
  73955. return task;
  73956. };
  73957. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  73958. var task = new BinaryFileAssetTask(taskName, url);
  73959. this.tasks.push(task);
  73960. return task;
  73961. };
  73962. AssetsManager.prototype.addImageTask = function (taskName, url) {
  73963. var task = new ImageAssetTask(taskName, url);
  73964. this.tasks.push(task);
  73965. return task;
  73966. };
  73967. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  73968. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73969. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  73970. this.tasks.push(task);
  73971. return task;
  73972. };
  73973. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  73974. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  73975. this.tasks.push(task);
  73976. return task;
  73977. };
  73978. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  73979. if (noMipmap === void 0) { noMipmap = false; }
  73980. if (generateHarmonics === void 0) { generateHarmonics = true; }
  73981. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  73982. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  73983. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  73984. this.tasks.push(task);
  73985. return task;
  73986. };
  73987. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  73988. this.waitingTasksCount--;
  73989. try {
  73990. if (this.onProgress) {
  73991. this.onProgress(this.waitingTasksCount, this.tasks.length, task);
  73992. }
  73993. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this.waitingTasksCount, this.tasks.length, task));
  73994. }
  73995. catch (e) {
  73996. BABYLON.Tools.Error("Error running progress callbacks.");
  73997. console.log(e);
  73998. }
  73999. if (this.waitingTasksCount === 0) {
  74000. try {
  74001. if (this.onFinish) {
  74002. this.onFinish(this.tasks);
  74003. }
  74004. this.onTasksDoneObservable.notifyObservers(this.tasks);
  74005. }
  74006. catch (e) {
  74007. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  74008. console.log(e);
  74009. }
  74010. this._scene.getEngine().hideLoadingUI();
  74011. }
  74012. };
  74013. AssetsManager.prototype._runTask = function (task) {
  74014. var _this = this;
  74015. var done = function () {
  74016. try {
  74017. if (_this.onTaskSuccess) {
  74018. _this.onTaskSuccess(task);
  74019. }
  74020. _this.onTaskSuccessObservable.notifyObservers(task);
  74021. _this._decreaseWaitingTasksCount(task);
  74022. }
  74023. catch (e) {
  74024. error("Error executing task success callbacks", e);
  74025. }
  74026. };
  74027. var error = function (message, exception) {
  74028. task.errorObject = task.errorObject || {
  74029. message: message,
  74030. exception: exception
  74031. };
  74032. if (_this.onTaskError) {
  74033. _this.onTaskError(task);
  74034. }
  74035. _this.onTaskErrorObservable.notifyObservers(task);
  74036. _this._decreaseWaitingTasksCount(task);
  74037. };
  74038. task.run(this._scene, done, error);
  74039. };
  74040. AssetsManager.prototype.reset = function () {
  74041. this.tasks = new Array();
  74042. return this;
  74043. };
  74044. AssetsManager.prototype.load = function () {
  74045. this.waitingTasksCount = this.tasks.length;
  74046. if (this.waitingTasksCount === 0) {
  74047. if (this.onFinish) {
  74048. this.onFinish(this.tasks);
  74049. }
  74050. this.onTasksDoneObservable.notifyObservers(this.tasks);
  74051. return this;
  74052. }
  74053. if (this.useDefaultLoadingScreen) {
  74054. this._scene.getEngine().displayLoadingUI();
  74055. }
  74056. for (var index = 0; index < this.tasks.length; index++) {
  74057. var task = this.tasks[index];
  74058. this._runTask(task);
  74059. }
  74060. return this;
  74061. };
  74062. return AssetsManager;
  74063. }());
  74064. BABYLON.AssetsManager = AssetsManager;
  74065. })(BABYLON || (BABYLON = {}));
  74066. //# sourceMappingURL=babylon.assetsManager.js.map
  74067. var BABYLON;
  74068. (function (BABYLON) {
  74069. var serializedGeometries = [];
  74070. var serializeGeometry = function (geometry, serializationGeometries) {
  74071. if (serializedGeometries[geometry.id]) {
  74072. return;
  74073. }
  74074. if (geometry.doNotSerialize) {
  74075. return;
  74076. }
  74077. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  74078. serializationGeometries.boxes.push(geometry.serialize());
  74079. }
  74080. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  74081. serializationGeometries.spheres.push(geometry.serialize());
  74082. }
  74083. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  74084. serializationGeometries.cylinders.push(geometry.serialize());
  74085. }
  74086. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  74087. serializationGeometries.toruses.push(geometry.serialize());
  74088. }
  74089. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  74090. serializationGeometries.grounds.push(geometry.serialize());
  74091. }
  74092. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  74093. serializationGeometries.planes.push(geometry.serialize());
  74094. }
  74095. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  74096. serializationGeometries.torusKnots.push(geometry.serialize());
  74097. }
  74098. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  74099. throw new Error("Unknown primitive type");
  74100. }
  74101. else {
  74102. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  74103. }
  74104. serializedGeometries[geometry.id] = true;
  74105. };
  74106. var serializeMesh = function (mesh, serializationScene) {
  74107. var serializationObject = {};
  74108. // Geometry
  74109. var geometry = mesh._geometry;
  74110. if (geometry) {
  74111. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  74112. // 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
  74113. serializeGeometry(geometry, serializationScene.geometries);
  74114. }
  74115. }
  74116. // Custom
  74117. if (mesh.serialize) {
  74118. mesh.serialize(serializationObject);
  74119. }
  74120. return serializationObject;
  74121. };
  74122. var finalizeSingleMesh = function (mesh, serializationObject) {
  74123. //only works if the mesh is already loaded
  74124. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  74125. //serialize material
  74126. if (mesh.material) {
  74127. if (mesh.material instanceof BABYLON.StandardMaterial) {
  74128. serializationObject.materials = serializationObject.materials || [];
  74129. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  74130. serializationObject.materials.push(mesh.material.serialize());
  74131. }
  74132. }
  74133. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  74134. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  74135. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  74136. serializationObject.multiMaterials.push(mesh.material.serialize());
  74137. }
  74138. }
  74139. }
  74140. //serialize geometry
  74141. var geometry = mesh._geometry;
  74142. if (geometry) {
  74143. if (!serializationObject.geometries) {
  74144. serializationObject.geometries = {};
  74145. serializationObject.geometries.boxes = [];
  74146. serializationObject.geometries.spheres = [];
  74147. serializationObject.geometries.cylinders = [];
  74148. serializationObject.geometries.toruses = [];
  74149. serializationObject.geometries.grounds = [];
  74150. serializationObject.geometries.planes = [];
  74151. serializationObject.geometries.torusKnots = [];
  74152. serializationObject.geometries.vertexData = [];
  74153. }
  74154. serializeGeometry(geometry, serializationObject.geometries);
  74155. }
  74156. // Skeletons
  74157. if (mesh.skeleton) {
  74158. serializationObject.skeletons = serializationObject.skeletons || [];
  74159. serializationObject.skeletons.push(mesh.skeleton.serialize());
  74160. }
  74161. //serialize the actual mesh
  74162. serializationObject.meshes = serializationObject.meshes || [];
  74163. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  74164. }
  74165. };
  74166. var SceneSerializer = /** @class */ (function () {
  74167. function SceneSerializer() {
  74168. }
  74169. SceneSerializer.ClearCache = function () {
  74170. serializedGeometries = [];
  74171. };
  74172. SceneSerializer.Serialize = function (scene) {
  74173. var serializationObject = {};
  74174. SceneSerializer.ClearCache();
  74175. // Scene
  74176. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  74177. serializationObject.autoClear = scene.autoClear;
  74178. serializationObject.clearColor = scene.clearColor.asArray();
  74179. serializationObject.ambientColor = scene.ambientColor.asArray();
  74180. serializationObject.gravity = scene.gravity.asArray();
  74181. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  74182. serializationObject.workerCollisions = scene.workerCollisions;
  74183. // Fog
  74184. if (scene.fogMode && scene.fogMode !== 0) {
  74185. serializationObject.fogMode = scene.fogMode;
  74186. serializationObject.fogColor = scene.fogColor.asArray();
  74187. serializationObject.fogStart = scene.fogStart;
  74188. serializationObject.fogEnd = scene.fogEnd;
  74189. serializationObject.fogDensity = scene.fogDensity;
  74190. }
  74191. //Physics
  74192. if (scene.isPhysicsEnabled()) {
  74193. var physicEngine = scene.getPhysicsEngine();
  74194. if (physicEngine) {
  74195. serializationObject.physicsEnabled = true;
  74196. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  74197. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  74198. }
  74199. }
  74200. // Metadata
  74201. if (scene.metadata) {
  74202. serializationObject.metadata = scene.metadata;
  74203. }
  74204. // Morph targets
  74205. serializationObject.morphTargetManagers = [];
  74206. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  74207. var abstractMesh = _a[_i];
  74208. var manager = abstractMesh.morphTargetManager;
  74209. if (manager) {
  74210. serializationObject.morphTargetManagers.push(manager.serialize());
  74211. }
  74212. }
  74213. // Lights
  74214. serializationObject.lights = [];
  74215. var index;
  74216. var light;
  74217. for (index = 0; index < scene.lights.length; index++) {
  74218. light = scene.lights[index];
  74219. if (!light.doNotSerialize) {
  74220. serializationObject.lights.push(light.serialize());
  74221. }
  74222. }
  74223. // Cameras
  74224. serializationObject.cameras = [];
  74225. for (index = 0; index < scene.cameras.length; index++) {
  74226. var camera = scene.cameras[index];
  74227. if (!camera.doNotSerialize) {
  74228. serializationObject.cameras.push(camera.serialize());
  74229. }
  74230. }
  74231. if (scene.activeCamera) {
  74232. serializationObject.activeCameraID = scene.activeCamera.id;
  74233. }
  74234. // Animations
  74235. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  74236. // Materials
  74237. serializationObject.materials = [];
  74238. serializationObject.multiMaterials = [];
  74239. var material;
  74240. for (index = 0; index < scene.materials.length; index++) {
  74241. material = scene.materials[index];
  74242. if (!material.doNotSerialize) {
  74243. serializationObject.materials.push(material.serialize());
  74244. }
  74245. }
  74246. // MultiMaterials
  74247. serializationObject.multiMaterials = [];
  74248. for (index = 0; index < scene.multiMaterials.length; index++) {
  74249. var multiMaterial = scene.multiMaterials[index];
  74250. serializationObject.multiMaterials.push(multiMaterial.serialize());
  74251. }
  74252. // Skeletons
  74253. serializationObject.skeletons = [];
  74254. for (index = 0; index < scene.skeletons.length; index++) {
  74255. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  74256. }
  74257. // Transform nodes
  74258. serializationObject.transformNodes = [];
  74259. for (index = 0; index < scene.transformNodes.length; index++) {
  74260. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  74261. }
  74262. // Geometries
  74263. serializationObject.geometries = {};
  74264. serializationObject.geometries.boxes = [];
  74265. serializationObject.geometries.spheres = [];
  74266. serializationObject.geometries.cylinders = [];
  74267. serializationObject.geometries.toruses = [];
  74268. serializationObject.geometries.grounds = [];
  74269. serializationObject.geometries.planes = [];
  74270. serializationObject.geometries.torusKnots = [];
  74271. serializationObject.geometries.vertexData = [];
  74272. serializedGeometries = [];
  74273. var geometries = scene.getGeometries();
  74274. for (index = 0; index < geometries.length; index++) {
  74275. var geometry = geometries[index];
  74276. if (geometry.isReady()) {
  74277. serializeGeometry(geometry, serializationObject.geometries);
  74278. }
  74279. }
  74280. // Meshes
  74281. serializationObject.meshes = [];
  74282. for (index = 0; index < scene.meshes.length; index++) {
  74283. var abstractMesh = scene.meshes[index];
  74284. if (abstractMesh instanceof BABYLON.Mesh) {
  74285. var mesh = abstractMesh;
  74286. if (!mesh.doNotSerialize) {
  74287. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  74288. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  74289. }
  74290. }
  74291. }
  74292. }
  74293. // Particles Systems
  74294. serializationObject.particleSystems = [];
  74295. for (index = 0; index < scene.particleSystems.length; index++) {
  74296. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  74297. }
  74298. // Lens flares
  74299. serializationObject.lensFlareSystems = [];
  74300. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  74301. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  74302. }
  74303. // Shadows
  74304. serializationObject.shadowGenerators = [];
  74305. for (index = 0; index < scene.lights.length; index++) {
  74306. light = scene.lights[index];
  74307. var shadowGenerator = light.getShadowGenerator();
  74308. if (shadowGenerator) {
  74309. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  74310. }
  74311. }
  74312. // Action Manager
  74313. if (scene.actionManager) {
  74314. serializationObject.actions = scene.actionManager.serialize("scene");
  74315. }
  74316. // Audio
  74317. serializationObject.sounds = [];
  74318. for (index = 0; index < scene.soundTracks.length; index++) {
  74319. var soundtrack = scene.soundTracks[index];
  74320. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  74321. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  74322. }
  74323. }
  74324. return serializationObject;
  74325. };
  74326. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  74327. if (withParents === void 0) { withParents = false; }
  74328. if (withChildren === void 0) { withChildren = false; }
  74329. var serializationObject = {};
  74330. SceneSerializer.ClearCache();
  74331. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  74332. if (withParents || withChildren) {
  74333. //deliberate for loop! not for each, appended should be processed as well.
  74334. for (var i = 0; i < toSerialize.length; ++i) {
  74335. if (withChildren) {
  74336. toSerialize[i].getDescendants().forEach(function (node) {
  74337. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  74338. toSerialize.push(node);
  74339. }
  74340. });
  74341. }
  74342. //make sure the array doesn't contain the object already
  74343. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  74344. toSerialize.push(toSerialize[i].parent);
  74345. }
  74346. }
  74347. }
  74348. toSerialize.forEach(function (mesh) {
  74349. finalizeSingleMesh(mesh, serializationObject);
  74350. });
  74351. return serializationObject;
  74352. };
  74353. return SceneSerializer;
  74354. }());
  74355. BABYLON.SceneSerializer = SceneSerializer;
  74356. })(BABYLON || (BABYLON = {}));
  74357. //# sourceMappingURL=babylon.sceneSerializer.js.map
  74358. var BABYLON;
  74359. (function (BABYLON) {
  74360. var ReflectionProbe = /** @class */ (function () {
  74361. function ReflectionProbe(name, size, scene, generateMipMaps) {
  74362. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74363. var _this = this;
  74364. this.name = name;
  74365. this._viewMatrix = BABYLON.Matrix.Identity();
  74366. this._target = BABYLON.Vector3.Zero();
  74367. this._add = BABYLON.Vector3.Zero();
  74368. this.invertYAxis = false;
  74369. this.position = BABYLON.Vector3.Zero();
  74370. this._scene = scene;
  74371. this._scene.reflectionProbes.push(this);
  74372. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  74373. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  74374. switch (faceIndex) {
  74375. case 0:
  74376. _this._add.copyFromFloats(1, 0, 0);
  74377. break;
  74378. case 1:
  74379. _this._add.copyFromFloats(-1, 0, 0);
  74380. break;
  74381. case 2:
  74382. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  74383. break;
  74384. case 3:
  74385. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  74386. break;
  74387. case 4:
  74388. _this._add.copyFromFloats(0, 0, 1);
  74389. break;
  74390. case 5:
  74391. _this._add.copyFromFloats(0, 0, -1);
  74392. break;
  74393. }
  74394. if (_this._attachedMesh) {
  74395. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  74396. }
  74397. _this.position.addToRef(_this._add, _this._target);
  74398. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  74399. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  74400. scene._forcedViewPosition = _this.position;
  74401. });
  74402. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  74403. scene._forcedViewPosition = null;
  74404. scene.updateTransformMatrix(true);
  74405. });
  74406. if (scene.activeCamera) {
  74407. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  74408. }
  74409. }
  74410. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  74411. get: function () {
  74412. return this._renderTargetTexture.samples;
  74413. },
  74414. set: function (value) {
  74415. this._renderTargetTexture.samples = value;
  74416. },
  74417. enumerable: true,
  74418. configurable: true
  74419. });
  74420. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  74421. get: function () {
  74422. return this._renderTargetTexture.refreshRate;
  74423. },
  74424. set: function (value) {
  74425. this._renderTargetTexture.refreshRate = value;
  74426. },
  74427. enumerable: true,
  74428. configurable: true
  74429. });
  74430. ReflectionProbe.prototype.getScene = function () {
  74431. return this._scene;
  74432. };
  74433. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  74434. get: function () {
  74435. return this._renderTargetTexture;
  74436. },
  74437. enumerable: true,
  74438. configurable: true
  74439. });
  74440. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  74441. get: function () {
  74442. return this._renderTargetTexture.renderList;
  74443. },
  74444. enumerable: true,
  74445. configurable: true
  74446. });
  74447. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  74448. this._attachedMesh = mesh;
  74449. };
  74450. /**
  74451. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  74452. *
  74453. * @param renderingGroupId The rendering group id corresponding to its index
  74454. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  74455. */
  74456. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  74457. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  74458. };
  74459. ReflectionProbe.prototype.dispose = function () {
  74460. var index = this._scene.reflectionProbes.indexOf(this);
  74461. if (index !== -1) {
  74462. // Remove from the scene if found
  74463. this._scene.reflectionProbes.splice(index, 1);
  74464. }
  74465. if (this._renderTargetTexture) {
  74466. this._renderTargetTexture.dispose();
  74467. this._renderTargetTexture = null;
  74468. }
  74469. };
  74470. return ReflectionProbe;
  74471. }());
  74472. BABYLON.ReflectionProbe = ReflectionProbe;
  74473. })(BABYLON || (BABYLON = {}));
  74474. //# sourceMappingURL=babylon.reflectionProbe.js.map
  74475. var BABYLON;
  74476. (function (BABYLON) {
  74477. var Layer = /** @class */ (function () {
  74478. function Layer(name, imgUrl, scene, isBackground, color) {
  74479. this.name = name;
  74480. this.scale = new BABYLON.Vector2(1, 1);
  74481. this.offset = new BABYLON.Vector2(0, 0);
  74482. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  74483. this.layerMask = 0x0FFFFFFF;
  74484. this._vertexBuffers = {};
  74485. // Events
  74486. /**
  74487. * An event triggered when the layer is disposed.
  74488. * @type {BABYLON.Observable}
  74489. */
  74490. this.onDisposeObservable = new BABYLON.Observable();
  74491. /**
  74492. * An event triggered before rendering the scene
  74493. * @type {BABYLON.Observable}
  74494. */
  74495. this.onBeforeRenderObservable = new BABYLON.Observable();
  74496. /**
  74497. * An event triggered after rendering the scene
  74498. * @type {BABYLON.Observable}
  74499. */
  74500. this.onAfterRenderObservable = new BABYLON.Observable();
  74501. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  74502. this.isBackground = isBackground === undefined ? true : isBackground;
  74503. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  74504. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  74505. this._scene.layers.push(this);
  74506. var engine = this._scene.getEngine();
  74507. // VBO
  74508. var vertices = [];
  74509. vertices.push(1, 1);
  74510. vertices.push(-1, 1);
  74511. vertices.push(-1, -1);
  74512. vertices.push(1, -1);
  74513. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74514. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  74515. this._createIndexBuffer();
  74516. // Effects
  74517. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  74518. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  74519. }
  74520. Object.defineProperty(Layer.prototype, "onDispose", {
  74521. set: function (callback) {
  74522. if (this._onDisposeObserver) {
  74523. this.onDisposeObservable.remove(this._onDisposeObserver);
  74524. }
  74525. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  74526. },
  74527. enumerable: true,
  74528. configurable: true
  74529. });
  74530. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  74531. set: function (callback) {
  74532. if (this._onBeforeRenderObserver) {
  74533. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  74534. }
  74535. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  74536. },
  74537. enumerable: true,
  74538. configurable: true
  74539. });
  74540. Object.defineProperty(Layer.prototype, "onAfterRender", {
  74541. set: function (callback) {
  74542. if (this._onAfterRenderObserver) {
  74543. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  74544. }
  74545. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  74546. },
  74547. enumerable: true,
  74548. configurable: true
  74549. });
  74550. Layer.prototype._createIndexBuffer = function () {
  74551. var engine = this._scene.getEngine();
  74552. // Indices
  74553. var indices = [];
  74554. indices.push(0);
  74555. indices.push(1);
  74556. indices.push(2);
  74557. indices.push(0);
  74558. indices.push(2);
  74559. indices.push(3);
  74560. this._indexBuffer = engine.createIndexBuffer(indices);
  74561. };
  74562. Layer.prototype._rebuild = function () {
  74563. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74564. if (vb) {
  74565. vb._rebuild();
  74566. }
  74567. this._createIndexBuffer();
  74568. };
  74569. Layer.prototype.render = function () {
  74570. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  74571. // Check
  74572. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  74573. return;
  74574. var engine = this._scene.getEngine();
  74575. this.onBeforeRenderObservable.notifyObservers(this);
  74576. // Render
  74577. engine.enableEffect(currentEffect);
  74578. engine.setState(false);
  74579. // Texture
  74580. currentEffect.setTexture("textureSampler", this.texture);
  74581. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  74582. // Color
  74583. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  74584. // Scale / offset
  74585. currentEffect.setVector2("offset", this.offset);
  74586. currentEffect.setVector2("scale", this.scale);
  74587. // VBOs
  74588. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  74589. // Draw order
  74590. if (!this.alphaTest) {
  74591. engine.setAlphaMode(this.alphaBlendingMode);
  74592. engine.draw(true, 0, 6);
  74593. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  74594. }
  74595. else {
  74596. engine.draw(true, 0, 6);
  74597. }
  74598. this.onAfterRenderObservable.notifyObservers(this);
  74599. };
  74600. Layer.prototype.dispose = function () {
  74601. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74602. if (vertexBuffer) {
  74603. vertexBuffer.dispose();
  74604. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74605. }
  74606. if (this._indexBuffer) {
  74607. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  74608. this._indexBuffer = null;
  74609. }
  74610. if (this.texture) {
  74611. this.texture.dispose();
  74612. this.texture = null;
  74613. }
  74614. // Remove from scene
  74615. var index = this._scene.layers.indexOf(this);
  74616. this._scene.layers.splice(index, 1);
  74617. // Callback
  74618. this.onDisposeObservable.notifyObservers(this);
  74619. this.onDisposeObservable.clear();
  74620. this.onAfterRenderObservable.clear();
  74621. this.onBeforeRenderObservable.clear();
  74622. };
  74623. return Layer;
  74624. }());
  74625. BABYLON.Layer = Layer;
  74626. })(BABYLON || (BABYLON = {}));
  74627. //# sourceMappingURL=babylon.layer.js.map
  74628. var BABYLON;
  74629. (function (BABYLON) {
  74630. var TextureTools = /** @class */ (function () {
  74631. function TextureTools() {
  74632. }
  74633. /**
  74634. * Uses the GPU to create a copy texture rescaled at a given size
  74635. * @param texture Texture to copy from
  74636. * @param width Desired width
  74637. * @param height Desired height
  74638. * @return Generated texture
  74639. */
  74640. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  74641. if (useBilinearMode === void 0) { useBilinearMode = true; }
  74642. var scene = texture.getScene();
  74643. var engine = scene.getEngine();
  74644. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  74645. rtt.wrapU = texture.wrapU;
  74646. rtt.wrapV = texture.wrapV;
  74647. rtt.uOffset = texture.uOffset;
  74648. rtt.vOffset = texture.vOffset;
  74649. rtt.uScale = texture.uScale;
  74650. rtt.vScale = texture.vScale;
  74651. rtt.uAng = texture.uAng;
  74652. rtt.vAng = texture.vAng;
  74653. rtt.wAng = texture.wAng;
  74654. rtt.coordinatesIndex = texture.coordinatesIndex;
  74655. rtt.level = texture.level;
  74656. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  74657. rtt._texture.isReady = false;
  74658. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74659. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74660. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74661. passPostProcess.getEffect().executeWhenCompiled(function () {
  74662. passPostProcess.onApply = function (effect) {
  74663. effect.setTexture("textureSampler", texture);
  74664. };
  74665. var internalTexture = rtt.getInternalTexture();
  74666. if (internalTexture) {
  74667. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  74668. engine.unBindFramebuffer(internalTexture);
  74669. rtt.disposeFramebufferObjects();
  74670. passPostProcess.dispose();
  74671. internalTexture.isReady = true;
  74672. }
  74673. });
  74674. return rtt;
  74675. };
  74676. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  74677. if (!scene._environmentBRDFTexture) {
  74678. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74679. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74680. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74681. scene._environmentBRDFTexture = texture;
  74682. }
  74683. return scene._environmentBRDFTexture;
  74684. };
  74685. 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=";
  74686. return TextureTools;
  74687. }());
  74688. BABYLON.TextureTools = TextureTools;
  74689. })(BABYLON || (BABYLON = {}));
  74690. //# sourceMappingURL=babylon.textureTools.js.map
  74691. var BABYLON;
  74692. (function (BABYLON) {
  74693. var FramingBehavior = /** @class */ (function () {
  74694. function FramingBehavior() {
  74695. this._mode = FramingBehavior.FitFrustumSidesMode;
  74696. this._radiusScale = 1.0;
  74697. this._positionScale = 0.5;
  74698. this._defaultElevation = 0.3;
  74699. this._elevationReturnTime = 1500;
  74700. this._elevationReturnWaitTime = 1000;
  74701. this._zoomStopsAnimation = false;
  74702. this._framingTime = 1500;
  74703. this._isPointerDown = false;
  74704. this._lastInteractionTime = -Infinity;
  74705. // Framing control
  74706. this._animatables = new Array();
  74707. this._betaIsAnimating = false;
  74708. }
  74709. Object.defineProperty(FramingBehavior.prototype, "name", {
  74710. get: function () {
  74711. return "Framing";
  74712. },
  74713. enumerable: true,
  74714. configurable: true
  74715. });
  74716. Object.defineProperty(FramingBehavior.prototype, "mode", {
  74717. /**
  74718. * Gets current mode used by the behavior.
  74719. */
  74720. get: function () {
  74721. return this._mode;
  74722. },
  74723. /**
  74724. * Sets the current mode used by the behavior
  74725. */
  74726. set: function (mode) {
  74727. this._mode = mode;
  74728. },
  74729. enumerable: true,
  74730. configurable: true
  74731. });
  74732. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  74733. /**
  74734. * Gets the scale applied to the radius
  74735. */
  74736. get: function () {
  74737. return this._radiusScale;
  74738. },
  74739. /**
  74740. * Sets the scale applied to the radius (1 by default)
  74741. */
  74742. set: function (radius) {
  74743. this._radiusScale = radius;
  74744. },
  74745. enumerable: true,
  74746. configurable: true
  74747. });
  74748. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  74749. /**
  74750. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  74751. */
  74752. get: function () {
  74753. return this._positionScale;
  74754. },
  74755. /**
  74756. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  74757. */
  74758. set: function (scale) {
  74759. this._positionScale = scale;
  74760. },
  74761. enumerable: true,
  74762. configurable: true
  74763. });
  74764. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  74765. /**
  74766. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  74767. * behaviour is triggered, in radians.
  74768. */
  74769. get: function () {
  74770. return this._defaultElevation;
  74771. },
  74772. /**
  74773. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  74774. * behaviour is triggered, in radians.
  74775. */
  74776. set: function (elevation) {
  74777. this._defaultElevation = elevation;
  74778. },
  74779. enumerable: true,
  74780. configurable: true
  74781. });
  74782. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  74783. /**
  74784. * Gets the time (in milliseconds) taken to return to the default beta position.
  74785. * Negative value indicates camera should not return to default.
  74786. */
  74787. get: function () {
  74788. return this._elevationReturnTime;
  74789. },
  74790. /**
  74791. * Sets the time (in milliseconds) taken to return to the default beta position.
  74792. * Negative value indicates camera should not return to default.
  74793. */
  74794. set: function (speed) {
  74795. this._elevationReturnTime = speed;
  74796. },
  74797. enumerable: true,
  74798. configurable: true
  74799. });
  74800. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  74801. /**
  74802. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  74803. */
  74804. get: function () {
  74805. return this._elevationReturnWaitTime;
  74806. },
  74807. /**
  74808. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  74809. */
  74810. set: function (time) {
  74811. this._elevationReturnWaitTime = time;
  74812. },
  74813. enumerable: true,
  74814. configurable: true
  74815. });
  74816. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  74817. /**
  74818. * Gets the flag that indicates if user zooming should stop animation.
  74819. */
  74820. get: function () {
  74821. return this._zoomStopsAnimation;
  74822. },
  74823. /**
  74824. * Sets the flag that indicates if user zooming should stop animation.
  74825. */
  74826. set: function (flag) {
  74827. this._zoomStopsAnimation = flag;
  74828. },
  74829. enumerable: true,
  74830. configurable: true
  74831. });
  74832. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  74833. /**
  74834. * Gets the transition time when framing the mesh, in milliseconds
  74835. */
  74836. get: function () {
  74837. return this._framingTime;
  74838. },
  74839. /**
  74840. * Sets the transition time when framing the mesh, in milliseconds
  74841. */
  74842. set: function (time) {
  74843. this._framingTime = time;
  74844. },
  74845. enumerable: true,
  74846. configurable: true
  74847. });
  74848. FramingBehavior.prototype.init = function () {
  74849. // Do notihng
  74850. };
  74851. FramingBehavior.prototype.attach = function (camera) {
  74852. var _this = this;
  74853. this._attachedCamera = camera;
  74854. var scene = this._attachedCamera.getScene();
  74855. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  74856. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  74857. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  74858. _this._isPointerDown = true;
  74859. return;
  74860. }
  74861. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  74862. _this._isPointerDown = false;
  74863. }
  74864. });
  74865. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  74866. if (mesh) {
  74867. _this.zoomOnMesh(mesh);
  74868. }
  74869. });
  74870. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  74871. // Stop the animation if there is user interaction and the animation should stop for this interaction
  74872. _this._applyUserInteraction();
  74873. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  74874. // back to the default position after a given timeout
  74875. _this._maintainCameraAboveGround();
  74876. });
  74877. };
  74878. FramingBehavior.prototype.detach = function () {
  74879. if (!this._attachedCamera) {
  74880. return;
  74881. }
  74882. var scene = this._attachedCamera.getScene();
  74883. if (this._onPrePointerObservableObserver) {
  74884. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  74885. }
  74886. if (this._onAfterCheckInputsObserver) {
  74887. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  74888. }
  74889. if (this._onMeshTargetChangedObserver) {
  74890. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  74891. }
  74892. this._attachedCamera = null;
  74893. };
  74894. /**
  74895. * Targets the given mesh and updates zoom level accordingly.
  74896. * @param mesh The mesh to target.
  74897. * @param radius Optional. If a cached radius position already exists, overrides default.
  74898. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  74899. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  74900. * @param onAnimationEnd Callback triggered at the end of the framing animation
  74901. */
  74902. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  74903. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  74904. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  74905. mesh.computeWorldMatrix(true);
  74906. var boundingBox = mesh.getBoundingInfo().boundingBox;
  74907. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  74908. };
  74909. /**
  74910. * Targets the given mesh with its children and updates zoom level accordingly.
  74911. * @param mesh The mesh to target.
  74912. * @param radius Optional. If a cached radius position already exists, overrides default.
  74913. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  74914. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  74915. * @param onAnimationEnd Callback triggered at the end of the framing animation
  74916. */
  74917. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  74918. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  74919. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  74920. mesh.computeWorldMatrix(true);
  74921. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  74922. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  74923. };
  74924. /**
  74925. * Targets the given meshes with their children and updates zoom level accordingly.
  74926. * @param meshes The mesh to target.
  74927. * @param radius Optional. If a cached radius position already exists, overrides default.
  74928. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  74929. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  74930. * @param onAnimationEnd Callback triggered at the end of the framing animation
  74931. */
  74932. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  74933. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  74934. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  74935. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  74936. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  74937. for (var i = 0; i < meshes.length; i++) {
  74938. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  74939. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  74940. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  74941. }
  74942. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  74943. };
  74944. /**
  74945. * Targets the given mesh and updates zoom level accordingly.
  74946. * @param mesh The mesh to target.
  74947. * @param radius Optional. If a cached radius position already exists, overrides default.
  74948. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  74949. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  74950. * @param onAnimationEnd Callback triggered at the end of the framing animation
  74951. */
  74952. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  74953. var _this = this;
  74954. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  74955. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  74956. var zoomTarget;
  74957. if (!this._attachedCamera) {
  74958. return;
  74959. }
  74960. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  74961. var bottom = minimumWorld.y;
  74962. var top = maximumWorld.y;
  74963. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  74964. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  74965. if (focusOnOriginXZ) {
  74966. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  74967. }
  74968. else {
  74969. var centerWorld = minimumWorld.add(radiusWorld);
  74970. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  74971. }
  74972. if (!this._vectorTransition) {
  74973. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  74974. }
  74975. this._betaIsAnimating = true;
  74976. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  74977. if (animatable) {
  74978. this._animatables.push(animatable);
  74979. }
  74980. // sets the radius and lower radius bounds
  74981. // Small delta ensures camera is not always at lower zoom limit.
  74982. var radius = 0;
  74983. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  74984. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  74985. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  74986. radius = position;
  74987. }
  74988. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  74989. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  74990. if (this._attachedCamera.lowerRadiusLimit === null) {
  74991. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  74992. }
  74993. }
  74994. // Set sensibilities
  74995. var extend = maximumWorld.subtract(minimumWorld).length();
  74996. this._attachedCamera.panningSensibility = 5000 / extend;
  74997. this._attachedCamera.wheelPrecision = 100 / radius;
  74998. // transition to new radius
  74999. if (!this._radiusTransition) {
  75000. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  75001. }
  75002. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  75003. if (onAnimationEnd) {
  75004. onAnimationEnd();
  75005. }
  75006. if (_this._attachedCamera) {
  75007. _this._attachedCamera.storeState();
  75008. }
  75009. });
  75010. if (animatable) {
  75011. this._animatables.push(animatable);
  75012. }
  75013. };
  75014. /**
  75015. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  75016. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  75017. * frustum width.
  75018. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  75019. * to fully enclose the mesh in the viewing frustum.
  75020. */
  75021. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  75022. var size = maximumWorld.subtract(minimumWorld);
  75023. var boxVectorGlobalDiagonal = size.length();
  75024. var frustumSlope = this._getFrustumSlope();
  75025. // Formula for setting distance
  75026. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  75027. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  75028. // Horizon distance
  75029. var radius = radiusWithoutFraming * this._radiusScale;
  75030. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  75031. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  75032. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  75033. var camera = this._attachedCamera;
  75034. if (!camera) {
  75035. return 0;
  75036. }
  75037. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  75038. // Don't exceed the requested limit
  75039. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  75040. }
  75041. // Don't exceed the upper radius limit
  75042. if (camera.upperRadiusLimit) {
  75043. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  75044. }
  75045. return distance;
  75046. };
  75047. /**
  75048. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  75049. * is automatically returned to its default position (expected to be above ground plane).
  75050. */
  75051. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  75052. var _this = this;
  75053. if (this._elevationReturnTime < 0) {
  75054. return;
  75055. }
  75056. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  75057. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  75058. var limitBeta = Math.PI * 0.5;
  75059. // Bring the camera back up if below the ground plane
  75060. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  75061. this._betaIsAnimating = true;
  75062. //Transition to new position
  75063. this.stopAllAnimations();
  75064. if (!this._betaTransition) {
  75065. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  75066. }
  75067. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  75068. _this._clearAnimationLocks();
  75069. _this.stopAllAnimations();
  75070. });
  75071. if (animatabe) {
  75072. this._animatables.push(animatabe);
  75073. }
  75074. }
  75075. };
  75076. /**
  75077. * Returns the frustum slope based on the canvas ratio and camera FOV
  75078. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  75079. */
  75080. FramingBehavior.prototype._getFrustumSlope = function () {
  75081. // Calculate the viewport ratio
  75082. // Aspect Ratio is Height/Width.
  75083. var camera = this._attachedCamera;
  75084. if (!camera) {
  75085. return BABYLON.Vector2.Zero();
  75086. }
  75087. var engine = camera.getScene().getEngine();
  75088. var aspectRatio = engine.getAspectRatio(camera);
  75089. // Camera FOV is the vertical field of view (top-bottom) in radians.
  75090. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  75091. var frustumSlopeY = Math.tan(camera.fov / 2);
  75092. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  75093. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  75094. // along the forward vector.
  75095. var frustumSlopeX = frustumSlopeY * aspectRatio;
  75096. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  75097. };
  75098. /**
  75099. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  75100. */
  75101. FramingBehavior.prototype._clearAnimationLocks = function () {
  75102. this._betaIsAnimating = false;
  75103. };
  75104. /**
  75105. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  75106. */
  75107. FramingBehavior.prototype._applyUserInteraction = function () {
  75108. if (this.isUserIsMoving) {
  75109. this._lastInteractionTime = BABYLON.Tools.Now;
  75110. this.stopAllAnimations();
  75111. this._clearAnimationLocks();
  75112. }
  75113. };
  75114. /**
  75115. * Stops and removes all animations that have been applied to the camera
  75116. */
  75117. FramingBehavior.prototype.stopAllAnimations = function () {
  75118. if (this._attachedCamera) {
  75119. this._attachedCamera.animations = [];
  75120. }
  75121. while (this._animatables.length) {
  75122. if (this._animatables[0]) {
  75123. this._animatables[0].onAnimationEnd = null;
  75124. this._animatables[0].stop();
  75125. }
  75126. this._animatables.shift();
  75127. }
  75128. };
  75129. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  75130. /**
  75131. * Gets a value indicating if the user is moving the camera
  75132. */
  75133. get: function () {
  75134. if (!this._attachedCamera) {
  75135. return false;
  75136. }
  75137. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  75138. this._attachedCamera.inertialBetaOffset !== 0 ||
  75139. this._attachedCamera.inertialRadiusOffset !== 0 ||
  75140. this._attachedCamera.inertialPanningX !== 0 ||
  75141. this._attachedCamera.inertialPanningY !== 0 ||
  75142. this._isPointerDown;
  75143. },
  75144. enumerable: true,
  75145. configurable: true
  75146. });
  75147. /**
  75148. * The easing function used by animations
  75149. */
  75150. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  75151. /**
  75152. * The easing mode used by animations
  75153. */
  75154. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  75155. // Statics
  75156. /**
  75157. * The camera can move all the way towards the mesh.
  75158. */
  75159. FramingBehavior.IgnoreBoundsSizeMode = 0;
  75160. /**
  75161. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  75162. */
  75163. FramingBehavior.FitFrustumSidesMode = 1;
  75164. return FramingBehavior;
  75165. }());
  75166. BABYLON.FramingBehavior = FramingBehavior;
  75167. })(BABYLON || (BABYLON = {}));
  75168. //# sourceMappingURL=babylon.framingBehavior.js.map
  75169. var BABYLON;
  75170. (function (BABYLON) {
  75171. /**
  75172. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  75173. */
  75174. var BouncingBehavior = /** @class */ (function () {
  75175. function BouncingBehavior() {
  75176. /**
  75177. * The duration of the animation, in milliseconds
  75178. */
  75179. this.transitionDuration = 450;
  75180. /**
  75181. * Length of the distance animated by the transition when lower radius is reached
  75182. */
  75183. this.lowerRadiusTransitionRange = 2;
  75184. /**
  75185. * Length of the distance animated by the transition when upper radius is reached
  75186. */
  75187. this.upperRadiusTransitionRange = -2;
  75188. this._autoTransitionRange = false;
  75189. // Animations
  75190. this._radiusIsAnimating = false;
  75191. this._radiusBounceTransition = null;
  75192. this._animatables = new Array();
  75193. }
  75194. Object.defineProperty(BouncingBehavior.prototype, "name", {
  75195. get: function () {
  75196. return "Bouncing";
  75197. },
  75198. enumerable: true,
  75199. configurable: true
  75200. });
  75201. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  75202. /**
  75203. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  75204. */
  75205. get: function () {
  75206. return this._autoTransitionRange;
  75207. },
  75208. /**
  75209. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  75210. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  75211. */
  75212. set: function (value) {
  75213. var _this = this;
  75214. if (this._autoTransitionRange === value) {
  75215. return;
  75216. }
  75217. this._autoTransitionRange = value;
  75218. var camera = this._attachedCamera;
  75219. if (!camera) {
  75220. return;
  75221. }
  75222. if (value) {
  75223. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  75224. if (!mesh) {
  75225. return;
  75226. }
  75227. mesh.computeWorldMatrix(true);
  75228. var diagonal = mesh.getBoundingInfo().diagonalLength;
  75229. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  75230. _this.upperRadiusTransitionRange = diagonal * 0.05;
  75231. });
  75232. }
  75233. else if (this._onMeshTargetChangedObserver) {
  75234. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  75235. }
  75236. },
  75237. enumerable: true,
  75238. configurable: true
  75239. });
  75240. BouncingBehavior.prototype.init = function () {
  75241. // Do notihng
  75242. };
  75243. BouncingBehavior.prototype.attach = function (camera) {
  75244. var _this = this;
  75245. this._attachedCamera = camera;
  75246. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  75247. if (!_this._attachedCamera) {
  75248. return;
  75249. }
  75250. // Add the bounce animation to the lower radius limit
  75251. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  75252. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  75253. }
  75254. // Add the bounce animation to the upper radius limit
  75255. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  75256. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  75257. }
  75258. });
  75259. };
  75260. BouncingBehavior.prototype.detach = function () {
  75261. if (!this._attachedCamera) {
  75262. return;
  75263. }
  75264. if (this._onAfterCheckInputsObserver) {
  75265. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  75266. }
  75267. if (this._onMeshTargetChangedObserver) {
  75268. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  75269. }
  75270. this._attachedCamera = null;
  75271. };
  75272. /**
  75273. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  75274. * @param radiusLimit The limit to check against.
  75275. * @return Bool to indicate if at limit.
  75276. */
  75277. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  75278. if (!this._attachedCamera) {
  75279. return false;
  75280. }
  75281. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  75282. return true;
  75283. }
  75284. return false;
  75285. };
  75286. /**
  75287. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  75288. * @param radiusDelta The delta by which to animate to. Can be negative.
  75289. */
  75290. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  75291. var _this = this;
  75292. if (!this._attachedCamera) {
  75293. return;
  75294. }
  75295. if (!this._radiusBounceTransition) {
  75296. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  75297. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  75298. }
  75299. // Prevent zoom until bounce has completed
  75300. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  75301. this._attachedCamera.wheelPrecision = Infinity;
  75302. this._attachedCamera.inertialRadiusOffset = 0;
  75303. // Animate to the radius limit
  75304. this.stopAllAnimations();
  75305. this._radiusIsAnimating = true;
  75306. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  75307. if (animatable) {
  75308. this._animatables.push(animatable);
  75309. }
  75310. };
  75311. /**
  75312. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  75313. */
  75314. BouncingBehavior.prototype._clearAnimationLocks = function () {
  75315. this._radiusIsAnimating = false;
  75316. if (this._attachedCamera) {
  75317. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  75318. }
  75319. };
  75320. /**
  75321. * Stops and removes all animations that have been applied to the camera
  75322. */
  75323. BouncingBehavior.prototype.stopAllAnimations = function () {
  75324. if (this._attachedCamera) {
  75325. this._attachedCamera.animations = [];
  75326. }
  75327. while (this._animatables.length) {
  75328. this._animatables[0].onAnimationEnd = null;
  75329. this._animatables[0].stop();
  75330. this._animatables.shift();
  75331. }
  75332. };
  75333. /**
  75334. * The easing function used by animations
  75335. */
  75336. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  75337. /**
  75338. * The easing mode used by animations
  75339. */
  75340. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  75341. return BouncingBehavior;
  75342. }());
  75343. BABYLON.BouncingBehavior = BouncingBehavior;
  75344. })(BABYLON || (BABYLON = {}));
  75345. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  75346. var BABYLON;
  75347. (function (BABYLON) {
  75348. var AutoRotationBehavior = /** @class */ (function () {
  75349. function AutoRotationBehavior() {
  75350. this._zoomStopsAnimation = false;
  75351. this._idleRotationSpeed = 0.05;
  75352. this._idleRotationWaitTime = 2000;
  75353. this._idleRotationSpinupTime = 2000;
  75354. this._isPointerDown = false;
  75355. this._lastFrameTime = null;
  75356. this._lastInteractionTime = -Infinity;
  75357. this._cameraRotationSpeed = 0;
  75358. this._lastFrameRadius = 0;
  75359. }
  75360. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  75361. get: function () {
  75362. return "AutoRotation";
  75363. },
  75364. enumerable: true,
  75365. configurable: true
  75366. });
  75367. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  75368. /**
  75369. * Gets the flag that indicates if user zooming should stop animation.
  75370. */
  75371. get: function () {
  75372. return this._zoomStopsAnimation;
  75373. },
  75374. /**
  75375. * Sets the flag that indicates if user zooming should stop animation.
  75376. */
  75377. set: function (flag) {
  75378. this._zoomStopsAnimation = flag;
  75379. },
  75380. enumerable: true,
  75381. configurable: true
  75382. });
  75383. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  75384. /**
  75385. * Gets the default speed at which the camera rotates around the model.
  75386. */
  75387. get: function () {
  75388. return this._idleRotationSpeed;
  75389. },
  75390. /**
  75391. * Sets the default speed at which the camera rotates around the model.
  75392. */
  75393. set: function (speed) {
  75394. this._idleRotationSpeed = speed;
  75395. },
  75396. enumerable: true,
  75397. configurable: true
  75398. });
  75399. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  75400. /**
  75401. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  75402. */
  75403. get: function () {
  75404. return this._idleRotationWaitTime;
  75405. },
  75406. /**
  75407. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  75408. */
  75409. set: function (time) {
  75410. this._idleRotationWaitTime = time;
  75411. },
  75412. enumerable: true,
  75413. configurable: true
  75414. });
  75415. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  75416. /**
  75417. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  75418. */
  75419. get: function () {
  75420. return this._idleRotationSpinupTime;
  75421. },
  75422. /**
  75423. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  75424. */
  75425. set: function (time) {
  75426. this._idleRotationSpinupTime = time;
  75427. },
  75428. enumerable: true,
  75429. configurable: true
  75430. });
  75431. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  75432. /**
  75433. * Gets a value indicating if the camera is currently rotating because of this behavior
  75434. */
  75435. get: function () {
  75436. return Math.abs(this._cameraRotationSpeed) > 0;
  75437. },
  75438. enumerable: true,
  75439. configurable: true
  75440. });
  75441. AutoRotationBehavior.prototype.init = function () {
  75442. // Do notihng
  75443. };
  75444. AutoRotationBehavior.prototype.attach = function (camera) {
  75445. var _this = this;
  75446. this._attachedCamera = camera;
  75447. var scene = this._attachedCamera.getScene();
  75448. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  75449. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  75450. _this._isPointerDown = true;
  75451. return;
  75452. }
  75453. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  75454. _this._isPointerDown = false;
  75455. }
  75456. });
  75457. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  75458. var now = BABYLON.Tools.Now;
  75459. var dt = 0;
  75460. if (_this._lastFrameTime != null) {
  75461. dt = now - _this._lastFrameTime;
  75462. }
  75463. _this._lastFrameTime = now;
  75464. // Stop the animation if there is user interaction and the animation should stop for this interaction
  75465. _this._applyUserInteraction();
  75466. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  75467. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  75468. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  75469. // Step camera rotation by rotation speed
  75470. if (_this._attachedCamera) {
  75471. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  75472. }
  75473. });
  75474. };
  75475. AutoRotationBehavior.prototype.detach = function () {
  75476. if (!this._attachedCamera) {
  75477. return;
  75478. }
  75479. var scene = this._attachedCamera.getScene();
  75480. if (this._onPrePointerObservableObserver) {
  75481. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  75482. }
  75483. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  75484. this._attachedCamera = null;
  75485. };
  75486. /**
  75487. * Returns true if user is scrolling.
  75488. * @return true if user is scrolling.
  75489. */
  75490. AutoRotationBehavior.prototype._userIsZooming = function () {
  75491. if (!this._attachedCamera) {
  75492. return false;
  75493. }
  75494. return this._attachedCamera.inertialRadiusOffset !== 0;
  75495. };
  75496. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  75497. if (!this._attachedCamera) {
  75498. return false;
  75499. }
  75500. var zoomHasHitLimit = false;
  75501. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  75502. zoomHasHitLimit = true;
  75503. }
  75504. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  75505. this._lastFrameRadius = this._attachedCamera.radius;
  75506. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  75507. };
  75508. /**
  75509. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  75510. */
  75511. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  75512. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  75513. this._lastInteractionTime = BABYLON.Tools.Now;
  75514. }
  75515. };
  75516. // Tools
  75517. AutoRotationBehavior.prototype._userIsMoving = function () {
  75518. if (!this._attachedCamera) {
  75519. return false;
  75520. }
  75521. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  75522. this._attachedCamera.inertialBetaOffset !== 0 ||
  75523. this._attachedCamera.inertialRadiusOffset !== 0 ||
  75524. this._attachedCamera.inertialPanningX !== 0 ||
  75525. this._attachedCamera.inertialPanningY !== 0 ||
  75526. this._isPointerDown;
  75527. };
  75528. return AutoRotationBehavior;
  75529. }());
  75530. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  75531. })(BABYLON || (BABYLON = {}));
  75532. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  75533. var BABYLON;
  75534. (function (BABYLON) {
  75535. /**
  75536. * This class can be used to get instrumentation data from a Babylon engine
  75537. */
  75538. var EngineInstrumentation = /** @class */ (function () {
  75539. function EngineInstrumentation(engine) {
  75540. this.engine = engine;
  75541. this._captureGPUFrameTime = false;
  75542. this._gpuFrameTime = new BABYLON.PerfCounter();
  75543. this._captureShaderCompilationTime = false;
  75544. this._shaderCompilationTime = new BABYLON.PerfCounter();
  75545. // Observers
  75546. this._onBeginFrameObserver = null;
  75547. this._onEndFrameObserver = null;
  75548. this._onBeforeShaderCompilationObserver = null;
  75549. this._onAfterShaderCompilationObserver = null;
  75550. }
  75551. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  75552. // Properties
  75553. /**
  75554. * Gets the perf counter used for GPU frame time
  75555. */
  75556. get: function () {
  75557. return this._gpuFrameTime;
  75558. },
  75559. enumerable: true,
  75560. configurable: true
  75561. });
  75562. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  75563. /**
  75564. * Gets the GPU frame time capture status
  75565. */
  75566. get: function () {
  75567. return this._captureGPUFrameTime;
  75568. },
  75569. /**
  75570. * Enable or disable the GPU frame time capture
  75571. */
  75572. set: function (value) {
  75573. var _this = this;
  75574. if (value === this._captureGPUFrameTime) {
  75575. return;
  75576. }
  75577. this._captureGPUFrameTime = value;
  75578. if (value) {
  75579. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  75580. if (!_this._gpuFrameTimeToken) {
  75581. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  75582. }
  75583. });
  75584. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  75585. if (!_this._gpuFrameTimeToken) {
  75586. return;
  75587. }
  75588. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  75589. if (time > -1) {
  75590. _this._gpuFrameTimeToken = null;
  75591. _this._gpuFrameTime.fetchNewFrame();
  75592. _this._gpuFrameTime.addCount(time, true);
  75593. }
  75594. });
  75595. }
  75596. else {
  75597. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  75598. this._onBeginFrameObserver = null;
  75599. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  75600. this._onEndFrameObserver = null;
  75601. }
  75602. },
  75603. enumerable: true,
  75604. configurable: true
  75605. });
  75606. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  75607. /**
  75608. * Gets the perf counter used for shader compilation time
  75609. */
  75610. get: function () {
  75611. return this._shaderCompilationTime;
  75612. },
  75613. enumerable: true,
  75614. configurable: true
  75615. });
  75616. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  75617. /**
  75618. * Gets the shader compilation time capture status
  75619. */
  75620. get: function () {
  75621. return this._captureShaderCompilationTime;
  75622. },
  75623. /**
  75624. * Enable or disable the shader compilation time capture
  75625. */
  75626. set: function (value) {
  75627. var _this = this;
  75628. if (value === this._captureShaderCompilationTime) {
  75629. return;
  75630. }
  75631. this._captureShaderCompilationTime = value;
  75632. if (value) {
  75633. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  75634. _this._shaderCompilationTime.fetchNewFrame();
  75635. _this._shaderCompilationTime.beginMonitoring();
  75636. });
  75637. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  75638. _this._shaderCompilationTime.endMonitoring();
  75639. });
  75640. }
  75641. else {
  75642. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  75643. this._onBeforeShaderCompilationObserver = null;
  75644. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  75645. this._onAfterShaderCompilationObserver = null;
  75646. }
  75647. },
  75648. enumerable: true,
  75649. configurable: true
  75650. });
  75651. EngineInstrumentation.prototype.dispose = function () {
  75652. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  75653. this._onBeginFrameObserver = null;
  75654. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  75655. this._onEndFrameObserver = null;
  75656. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  75657. this._onBeforeShaderCompilationObserver = null;
  75658. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  75659. this._onAfterShaderCompilationObserver = null;
  75660. this.engine = null;
  75661. };
  75662. return EngineInstrumentation;
  75663. }());
  75664. BABYLON.EngineInstrumentation = EngineInstrumentation;
  75665. })(BABYLON || (BABYLON = {}));
  75666. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  75667. var BABYLON;
  75668. (function (BABYLON) {
  75669. /**
  75670. * This class can be used to get instrumentation data from a Babylon engine
  75671. */
  75672. var SceneInstrumentation = /** @class */ (function () {
  75673. function SceneInstrumentation(scene) {
  75674. var _this = this;
  75675. this.scene = scene;
  75676. this._captureActiveMeshesEvaluationTime = false;
  75677. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  75678. this._captureRenderTargetsRenderTime = false;
  75679. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  75680. this._captureFrameTime = false;
  75681. this._frameTime = new BABYLON.PerfCounter();
  75682. this._captureRenderTime = false;
  75683. this._renderTime = new BABYLON.PerfCounter();
  75684. this._captureInterFrameTime = false;
  75685. this._interFrameTime = new BABYLON.PerfCounter();
  75686. this._captureParticlesRenderTime = false;
  75687. this._particlesRenderTime = new BABYLON.PerfCounter();
  75688. this._captureSpritesRenderTime = false;
  75689. this._spritesRenderTime = new BABYLON.PerfCounter();
  75690. this._capturePhysicsTime = false;
  75691. this._physicsTime = new BABYLON.PerfCounter();
  75692. this._captureAnimationsTime = false;
  75693. this._animationsTime = new BABYLON.PerfCounter();
  75694. // Observers
  75695. this._onBeforeActiveMeshesEvaluationObserver = null;
  75696. this._onAfterActiveMeshesEvaluationObserver = null;
  75697. this._onBeforeRenderTargetsRenderObserver = null;
  75698. this._onAfterRenderTargetsRenderObserver = null;
  75699. this._onAfterRenderObserver = null;
  75700. this._onBeforeDrawPhaseObserver = null;
  75701. this._onAfterDrawPhaseObserver = null;
  75702. this._onBeforeAnimationsObserver = null;
  75703. this._onBeforeParticlesRenderingObserver = null;
  75704. this._onAfterParticlesRenderingObserver = null;
  75705. this._onBeforeSpritesRenderingObserver = null;
  75706. this._onAfterSpritesRenderingObserver = null;
  75707. this._onBeforePhysicsObserver = null;
  75708. this._onAfterPhysicsObserver = null;
  75709. this._onAfterAnimationsObserver = null;
  75710. // Before render
  75711. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  75712. if (_this._captureActiveMeshesEvaluationTime) {
  75713. _this._activeMeshesEvaluationTime.fetchNewFrame();
  75714. }
  75715. if (_this._captureRenderTargetsRenderTime) {
  75716. _this._renderTargetsRenderTime.fetchNewFrame();
  75717. }
  75718. if (_this._captureFrameTime) {
  75719. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  75720. _this._frameTime.beginMonitoring();
  75721. }
  75722. if (_this._captureInterFrameTime) {
  75723. _this._interFrameTime.endMonitoring();
  75724. }
  75725. if (_this._captureParticlesRenderTime) {
  75726. _this._particlesRenderTime.fetchNewFrame();
  75727. }
  75728. if (_this._captureSpritesRenderTime) {
  75729. _this._spritesRenderTime.fetchNewFrame();
  75730. }
  75731. if (_this._captureAnimationsTime) {
  75732. _this._animationsTime.beginMonitoring();
  75733. }
  75734. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  75735. });
  75736. // After render
  75737. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  75738. if (_this._captureFrameTime) {
  75739. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  75740. _this._frameTime.endMonitoring();
  75741. }
  75742. if (_this._captureRenderTime) {
  75743. _this._renderTime.endMonitoring(false);
  75744. }
  75745. if (_this._captureInterFrameTime) {
  75746. _this._interFrameTime.beginMonitoring();
  75747. }
  75748. });
  75749. }
  75750. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  75751. // Properties
  75752. /**
  75753. * Gets the perf counter used for active meshes evaluation time
  75754. */
  75755. get: function () {
  75756. return this._activeMeshesEvaluationTime;
  75757. },
  75758. enumerable: true,
  75759. configurable: true
  75760. });
  75761. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  75762. /**
  75763. * Gets the active meshes evaluation time capture status
  75764. */
  75765. get: function () {
  75766. return this._captureActiveMeshesEvaluationTime;
  75767. },
  75768. /**
  75769. * Enable or disable the active meshes evaluation time capture
  75770. */
  75771. set: function (value) {
  75772. var _this = this;
  75773. if (value === this._captureActiveMeshesEvaluationTime) {
  75774. return;
  75775. }
  75776. this._captureActiveMeshesEvaluationTime = value;
  75777. if (value) {
  75778. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  75779. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  75780. _this._activeMeshesEvaluationTime.beginMonitoring();
  75781. });
  75782. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  75783. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  75784. _this._activeMeshesEvaluationTime.endMonitoring();
  75785. });
  75786. }
  75787. else {
  75788. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  75789. this._onBeforeActiveMeshesEvaluationObserver = null;
  75790. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  75791. this._onAfterActiveMeshesEvaluationObserver = null;
  75792. }
  75793. },
  75794. enumerable: true,
  75795. configurable: true
  75796. });
  75797. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  75798. /**
  75799. * Gets the perf counter used for render targets render time
  75800. */
  75801. get: function () {
  75802. return this._renderTargetsRenderTime;
  75803. },
  75804. enumerable: true,
  75805. configurable: true
  75806. });
  75807. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  75808. /**
  75809. * Gets the render targets render time capture status
  75810. */
  75811. get: function () {
  75812. return this._captureRenderTargetsRenderTime;
  75813. },
  75814. /**
  75815. * Enable or disable the render targets render time capture
  75816. */
  75817. set: function (value) {
  75818. var _this = this;
  75819. if (value === this._captureRenderTargetsRenderTime) {
  75820. return;
  75821. }
  75822. this._captureRenderTargetsRenderTime = value;
  75823. if (value) {
  75824. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  75825. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  75826. _this._renderTargetsRenderTime.beginMonitoring();
  75827. });
  75828. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  75829. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  75830. _this._renderTargetsRenderTime.endMonitoring(false);
  75831. });
  75832. }
  75833. else {
  75834. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  75835. this._onBeforeRenderTargetsRenderObserver = null;
  75836. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  75837. this._onAfterRenderTargetsRenderObserver = null;
  75838. }
  75839. },
  75840. enumerable: true,
  75841. configurable: true
  75842. });
  75843. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  75844. /**
  75845. * Gets the perf counter used for particles render time
  75846. */
  75847. get: function () {
  75848. return this._particlesRenderTime;
  75849. },
  75850. enumerable: true,
  75851. configurable: true
  75852. });
  75853. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  75854. /**
  75855. * Gets the particles render time capture status
  75856. */
  75857. get: function () {
  75858. return this._captureParticlesRenderTime;
  75859. },
  75860. /**
  75861. * Enable or disable the particles render time capture
  75862. */
  75863. set: function (value) {
  75864. var _this = this;
  75865. if (value === this._captureParticlesRenderTime) {
  75866. return;
  75867. }
  75868. this._captureParticlesRenderTime = value;
  75869. if (value) {
  75870. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  75871. BABYLON.Tools.StartPerformanceCounter("Particles");
  75872. _this._particlesRenderTime.beginMonitoring();
  75873. });
  75874. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  75875. BABYLON.Tools.EndPerformanceCounter("Particles");
  75876. _this._particlesRenderTime.endMonitoring(false);
  75877. });
  75878. }
  75879. else {
  75880. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  75881. this._onBeforeParticlesRenderingObserver = null;
  75882. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  75883. this._onAfterParticlesRenderingObserver = null;
  75884. }
  75885. },
  75886. enumerable: true,
  75887. configurable: true
  75888. });
  75889. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  75890. /**
  75891. * Gets the perf counter used for sprites render time
  75892. */
  75893. get: function () {
  75894. return this._spritesRenderTime;
  75895. },
  75896. enumerable: true,
  75897. configurable: true
  75898. });
  75899. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  75900. /**
  75901. * Gets the sprites render time capture status
  75902. */
  75903. get: function () {
  75904. return this._captureSpritesRenderTime;
  75905. },
  75906. /**
  75907. * Enable or disable the sprites render time capture
  75908. */
  75909. set: function (value) {
  75910. var _this = this;
  75911. if (value === this._captureSpritesRenderTime) {
  75912. return;
  75913. }
  75914. this._captureSpritesRenderTime = value;
  75915. if (value) {
  75916. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  75917. BABYLON.Tools.StartPerformanceCounter("Sprites");
  75918. _this._spritesRenderTime.beginMonitoring();
  75919. });
  75920. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  75921. BABYLON.Tools.EndPerformanceCounter("Sprites");
  75922. _this._spritesRenderTime.endMonitoring(false);
  75923. });
  75924. }
  75925. else {
  75926. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  75927. this._onBeforeSpritesRenderingObserver = null;
  75928. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  75929. this._onAfterSpritesRenderingObserver = null;
  75930. }
  75931. },
  75932. enumerable: true,
  75933. configurable: true
  75934. });
  75935. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  75936. /**
  75937. * Gets the perf counter used for physics time
  75938. */
  75939. get: function () {
  75940. return this._physicsTime;
  75941. },
  75942. enumerable: true,
  75943. configurable: true
  75944. });
  75945. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  75946. /**
  75947. * Gets the physics time capture status
  75948. */
  75949. get: function () {
  75950. return this._capturePhysicsTime;
  75951. },
  75952. /**
  75953. * Enable or disable the physics time capture
  75954. */
  75955. set: function (value) {
  75956. var _this = this;
  75957. if (value === this._capturePhysicsTime) {
  75958. return;
  75959. }
  75960. this._capturePhysicsTime = value;
  75961. if (value) {
  75962. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  75963. BABYLON.Tools.StartPerformanceCounter("Physics");
  75964. _this._physicsTime.beginMonitoring();
  75965. });
  75966. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  75967. BABYLON.Tools.EndPerformanceCounter("Physics");
  75968. _this._physicsTime.endMonitoring();
  75969. });
  75970. }
  75971. else {
  75972. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  75973. this._onBeforePhysicsObserver = null;
  75974. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  75975. this._onAfterPhysicsObserver = null;
  75976. }
  75977. },
  75978. enumerable: true,
  75979. configurable: true
  75980. });
  75981. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  75982. /**
  75983. * Gets the perf counter used for animations time
  75984. */
  75985. get: function () {
  75986. return this._animationsTime;
  75987. },
  75988. enumerable: true,
  75989. configurable: true
  75990. });
  75991. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  75992. /**
  75993. * Gets the animations time capture status
  75994. */
  75995. get: function () {
  75996. return this._captureAnimationsTime;
  75997. },
  75998. /**
  75999. * Enable or disable the animations time capture
  76000. */
  76001. set: function (value) {
  76002. var _this = this;
  76003. if (value === this._captureAnimationsTime) {
  76004. return;
  76005. }
  76006. this._captureAnimationsTime = value;
  76007. if (value) {
  76008. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  76009. _this._animationsTime.endMonitoring();
  76010. });
  76011. }
  76012. else {
  76013. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  76014. this._onAfterAnimationsObserver = null;
  76015. }
  76016. },
  76017. enumerable: true,
  76018. configurable: true
  76019. });
  76020. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  76021. /**
  76022. * Gets the perf counter used for frame time capture
  76023. */
  76024. get: function () {
  76025. return this._frameTime;
  76026. },
  76027. enumerable: true,
  76028. configurable: true
  76029. });
  76030. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  76031. /**
  76032. * Gets the frame time capture status
  76033. */
  76034. get: function () {
  76035. return this._captureFrameTime;
  76036. },
  76037. /**
  76038. * Enable or disable the frame time capture
  76039. */
  76040. set: function (value) {
  76041. this._captureFrameTime = value;
  76042. },
  76043. enumerable: true,
  76044. configurable: true
  76045. });
  76046. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  76047. /**
  76048. * Gets the perf counter used for inter-frames time capture
  76049. */
  76050. get: function () {
  76051. return this._interFrameTime;
  76052. },
  76053. enumerable: true,
  76054. configurable: true
  76055. });
  76056. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  76057. /**
  76058. * Gets the inter-frames time capture status
  76059. */
  76060. get: function () {
  76061. return this._captureInterFrameTime;
  76062. },
  76063. /**
  76064. * Enable or disable the inter-frames time capture
  76065. */
  76066. set: function (value) {
  76067. this._captureInterFrameTime = value;
  76068. },
  76069. enumerable: true,
  76070. configurable: true
  76071. });
  76072. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  76073. /**
  76074. * Gets the perf counter used for render time capture
  76075. */
  76076. get: function () {
  76077. return this._renderTime;
  76078. },
  76079. enumerable: true,
  76080. configurable: true
  76081. });
  76082. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  76083. /**
  76084. * Gets the render time capture status
  76085. */
  76086. get: function () {
  76087. return this._captureRenderTime;
  76088. },
  76089. /**
  76090. * Enable or disable the render time capture
  76091. */
  76092. set: function (value) {
  76093. var _this = this;
  76094. if (value === this._captureRenderTime) {
  76095. return;
  76096. }
  76097. this._captureRenderTime = value;
  76098. if (value) {
  76099. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  76100. _this._renderTime.beginMonitoring();
  76101. BABYLON.Tools.StartPerformanceCounter("Main render");
  76102. });
  76103. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  76104. _this._renderTime.endMonitoring(false);
  76105. BABYLON.Tools.EndPerformanceCounter("Main render");
  76106. });
  76107. }
  76108. else {
  76109. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  76110. this._onBeforeDrawPhaseObserver = null;
  76111. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  76112. this._onAfterDrawPhaseObserver = null;
  76113. }
  76114. },
  76115. enumerable: true,
  76116. configurable: true
  76117. });
  76118. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  76119. /**
  76120. * Gets the perf counter used for frame time capture
  76121. */
  76122. get: function () {
  76123. return this.scene.getEngine()._drawCalls;
  76124. },
  76125. enumerable: true,
  76126. configurable: true
  76127. });
  76128. SceneInstrumentation.prototype.dispose = function () {
  76129. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  76130. this._onAfterRenderObserver = null;
  76131. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  76132. this._onBeforeActiveMeshesEvaluationObserver = null;
  76133. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  76134. this._onAfterActiveMeshesEvaluationObserver = null;
  76135. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  76136. this._onBeforeRenderTargetsRenderObserver = null;
  76137. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  76138. this._onAfterRenderTargetsRenderObserver = null;
  76139. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  76140. this._onBeforeAnimationsObserver = null;
  76141. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  76142. this._onBeforeParticlesRenderingObserver = null;
  76143. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  76144. this._onAfterParticlesRenderingObserver = null;
  76145. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  76146. this._onBeforeSpritesRenderingObserver = null;
  76147. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  76148. this._onAfterSpritesRenderingObserver = null;
  76149. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  76150. this._onBeforeDrawPhaseObserver = null;
  76151. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  76152. this._onAfterDrawPhaseObserver = null;
  76153. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  76154. this._onBeforePhysicsObserver = null;
  76155. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  76156. this._onAfterPhysicsObserver = null;
  76157. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  76158. this._onAfterAnimationsObserver = null;
  76159. this.scene = null;
  76160. };
  76161. return SceneInstrumentation;
  76162. }());
  76163. BABYLON.SceneInstrumentation = SceneInstrumentation;
  76164. })(BABYLON || (BABYLON = {}));
  76165. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  76166. var BABYLON;
  76167. (function (BABYLON) {
  76168. var _TimeToken = /** @class */ (function () {
  76169. function _TimeToken() {
  76170. this._timeElapsedQueryEnded = false;
  76171. }
  76172. return _TimeToken;
  76173. }());
  76174. BABYLON._TimeToken = _TimeToken;
  76175. })(BABYLON || (BABYLON = {}));
  76176. //# sourceMappingURL=babylon.timeToken.js.map
  76177. var BABYLON;
  76178. (function (BABYLON) {
  76179. /**
  76180. * Background material defines definition.
  76181. */
  76182. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  76183. __extends(BackgroundMaterialDefines, _super);
  76184. /**
  76185. * Constructor of the defines.
  76186. */
  76187. function BackgroundMaterialDefines() {
  76188. var _this = _super.call(this) || this;
  76189. /**
  76190. * True if the diffuse texture is in use.
  76191. */
  76192. _this.DIFFUSE = false;
  76193. /**
  76194. * The direct UV channel to use.
  76195. */
  76196. _this.DIFFUSEDIRECTUV = 0;
  76197. /**
  76198. * True if the diffuse texture is in gamma space.
  76199. */
  76200. _this.GAMMADIFFUSE = false;
  76201. /**
  76202. * True if the diffuse texture has opacity in the alpha channel.
  76203. */
  76204. _this.DIFFUSEHASALPHA = false;
  76205. /**
  76206. * True if you want the material to fade to transparent at grazing angle.
  76207. */
  76208. _this.OPACITYFRESNEL = false;
  76209. /**
  76210. * True if an extra blur needs to be added in the reflection.
  76211. */
  76212. _this.REFLECTIONBLUR = false;
  76213. /**
  76214. * True if you want the material to fade to reflection at grazing angle.
  76215. */
  76216. _this.REFLECTIONFRESNEL = false;
  76217. /**
  76218. * True if you want the material to falloff as far as you move away from the scene center.
  76219. */
  76220. _this.REFLECTIONFALLOFF = false;
  76221. /**
  76222. * False if the current Webgl implementation does not support the texture lod extension.
  76223. */
  76224. _this.TEXTURELODSUPPORT = false;
  76225. /**
  76226. * True to ensure the data are premultiplied.
  76227. */
  76228. _this.PREMULTIPLYALPHA = false;
  76229. /**
  76230. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  76231. */
  76232. _this.USERGBCOLOR = false;
  76233. /**
  76234. * True to add noise in order to reduce the banding effect.
  76235. */
  76236. _this.NOISE = false;
  76237. // Image Processing Configuration.
  76238. _this.IMAGEPROCESSING = false;
  76239. _this.VIGNETTE = false;
  76240. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  76241. _this.VIGNETTEBLENDMODEOPAQUE = false;
  76242. _this.TONEMAPPING = false;
  76243. _this.CONTRAST = false;
  76244. _this.COLORCURVES = false;
  76245. _this.COLORGRADING = false;
  76246. _this.COLORGRADING3D = false;
  76247. _this.SAMPLER3DGREENDEPTH = false;
  76248. _this.SAMPLER3DBGRMAP = false;
  76249. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  76250. _this.EXPOSURE = false;
  76251. // Reflection.
  76252. _this.REFLECTION = false;
  76253. _this.REFLECTIONMAP_3D = false;
  76254. _this.REFLECTIONMAP_SPHERICAL = false;
  76255. _this.REFLECTIONMAP_PLANAR = false;
  76256. _this.REFLECTIONMAP_CUBIC = false;
  76257. _this.REFLECTIONMAP_PROJECTION = false;
  76258. _this.REFLECTIONMAP_SKYBOX = false;
  76259. _this.REFLECTIONMAP_EXPLICIT = false;
  76260. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  76261. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  76262. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  76263. _this.INVERTCUBICMAP = false;
  76264. _this.REFLECTIONMAP_OPPOSITEZ = false;
  76265. _this.LODINREFLECTIONALPHA = false;
  76266. _this.GAMMAREFLECTION = false;
  76267. // Default BJS.
  76268. _this.MAINUV1 = false;
  76269. _this.MAINUV2 = false;
  76270. _this.UV1 = false;
  76271. _this.UV2 = false;
  76272. _this.CLIPPLANE = false;
  76273. _this.POINTSIZE = false;
  76274. _this.FOG = false;
  76275. _this.NORMAL = false;
  76276. _this.NUM_BONE_INFLUENCERS = 0;
  76277. _this.BonesPerMesh = 0;
  76278. _this.INSTANCES = false;
  76279. _this.SHADOWFLOAT = false;
  76280. _this.rebuild();
  76281. return _this;
  76282. }
  76283. return BackgroundMaterialDefines;
  76284. }(BABYLON.MaterialDefines));
  76285. /**
  76286. * Background material used to create an efficient environement around your scene.
  76287. */
  76288. var BackgroundMaterial = /** @class */ (function (_super) {
  76289. __extends(BackgroundMaterial, _super);
  76290. /**
  76291. * constructor
  76292. * @param name The name of the material
  76293. * @param scene The scene to add the material to
  76294. */
  76295. function BackgroundMaterial(name, scene) {
  76296. var _this = _super.call(this, name, scene) || this;
  76297. _this.primaryColor = BABYLON.Color3.White();
  76298. _this.primaryLevel = 1;
  76299. _this.secondaryColor = BABYLON.Color3.Gray();
  76300. _this.secondaryLevel = 1;
  76301. _this.tertiaryColor = BABYLON.Color3.Black();
  76302. _this.tertiaryLevel = 1;
  76303. _this.reflectionTexture = null;
  76304. _this.reflectionBlur = 0;
  76305. _this.diffuseTexture = null;
  76306. /**
  76307. * Specify the list of lights casting shadow on the material.
  76308. * All scene shadow lights will be included if null.
  76309. */
  76310. _this._shadowLights = null;
  76311. _this.shadowLights = null;
  76312. _this.shadowBlurScale = 1;
  76313. _this.shadowLevel = 0;
  76314. _this.sceneCenter = BABYLON.Vector3.Zero();
  76315. _this.opacityFresnel = true;
  76316. _this.reflectionFresnel = false;
  76317. _this.reflectionFalloffDistance = 0.0;
  76318. _this.reflectionAmount = 1.0;
  76319. _this.reflectionReflectance0 = 0.05;
  76320. _this.reflectionReflectance90 = 0.5;
  76321. _this.useRGBColor = true;
  76322. _this.enableNoise = false;
  76323. /**
  76324. * Number of Simultaneous lights allowed on the material.
  76325. */
  76326. _this._maxSimultaneousLights = 4;
  76327. _this.maxSimultaneousLights = 4;
  76328. /**
  76329. * Keep track of the image processing observer to allow dispose and replace.
  76330. */
  76331. _this._imageProcessingObserver = null;
  76332. // Temp values kept as cache in the material.
  76333. _this._renderTargets = new BABYLON.SmartArray(16);
  76334. _this._reflectionControls = BABYLON.Vector4.Zero();
  76335. // Setup the default processing configuration to the scene.
  76336. _this._attachImageProcessingConfiguration(null);
  76337. _this.getRenderTargetTextures = function () {
  76338. _this._renderTargets.reset();
  76339. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  76340. _this._renderTargets.push(_this._diffuseTexture);
  76341. }
  76342. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  76343. _this._renderTargets.push(_this._reflectionTexture);
  76344. }
  76345. return _this._renderTargets;
  76346. };
  76347. return _this;
  76348. }
  76349. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  76350. /**
  76351. * Sets the reflection reflectance fresnel values according to the default standard
  76352. * empirically know to work well :-)
  76353. */
  76354. set: function (value) {
  76355. var reflectionWeight = value;
  76356. if (reflectionWeight < 0.5) {
  76357. reflectionWeight = reflectionWeight * 2.0;
  76358. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 * reflectionWeight;
  76359. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 * reflectionWeight;
  76360. }
  76361. else {
  76362. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  76363. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 + (1.0 - BackgroundMaterial.standardReflectance0) * reflectionWeight;
  76364. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 + (1.0 - BackgroundMaterial.standardReflectance90) * reflectionWeight;
  76365. }
  76366. },
  76367. enumerable: true,
  76368. configurable: true
  76369. });
  76370. /**
  76371. * Attaches a new image processing configuration to the PBR Material.
  76372. * @param configuration (if null the scene configuration will be use)
  76373. */
  76374. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  76375. var _this = this;
  76376. if (configuration === this._imageProcessingConfiguration) {
  76377. return;
  76378. }
  76379. // Detaches observer.
  76380. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  76381. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  76382. }
  76383. // Pick the scene configuration if needed.
  76384. if (!configuration) {
  76385. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  76386. }
  76387. else {
  76388. this._imageProcessingConfiguration = configuration;
  76389. }
  76390. // Attaches observer.
  76391. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  76392. _this._markAllSubMeshesAsImageProcessingDirty();
  76393. });
  76394. };
  76395. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  76396. /**
  76397. * Gets the image processing configuration used either in this material.
  76398. */
  76399. get: function () {
  76400. return this._imageProcessingConfiguration;
  76401. },
  76402. /**
  76403. * Sets the Default image processing configuration used either in the this material.
  76404. *
  76405. * If sets to null, the scene one is in use.
  76406. */
  76407. set: function (value) {
  76408. this._attachImageProcessingConfiguration(value);
  76409. // Ensure the effect will be rebuilt.
  76410. this._markAllSubMeshesAsTexturesDirty();
  76411. },
  76412. enumerable: true,
  76413. configurable: true
  76414. });
  76415. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  76416. /**
  76417. * Gets wether the color curves effect is enabled.
  76418. */
  76419. get: function () {
  76420. return this.imageProcessingConfiguration.colorCurvesEnabled;
  76421. },
  76422. /**
  76423. * Sets wether the color curves effect is enabled.
  76424. */
  76425. set: function (value) {
  76426. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  76427. },
  76428. enumerable: true,
  76429. configurable: true
  76430. });
  76431. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  76432. /**
  76433. * Gets wether the color grading effect is enabled.
  76434. */
  76435. get: function () {
  76436. return this.imageProcessingConfiguration.colorGradingEnabled;
  76437. },
  76438. /**
  76439. * Gets wether the color grading effect is enabled.
  76440. */
  76441. set: function (value) {
  76442. this.imageProcessingConfiguration.colorGradingEnabled = value;
  76443. },
  76444. enumerable: true,
  76445. configurable: true
  76446. });
  76447. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  76448. /**
  76449. * Gets wether tonemapping is enabled or not.
  76450. */
  76451. get: function () {
  76452. return this._imageProcessingConfiguration.toneMappingEnabled;
  76453. },
  76454. /**
  76455. * Sets wether tonemapping is enabled or not
  76456. */
  76457. set: function (value) {
  76458. this._imageProcessingConfiguration.toneMappingEnabled = value;
  76459. },
  76460. enumerable: true,
  76461. configurable: true
  76462. });
  76463. ;
  76464. ;
  76465. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  76466. /**
  76467. * The camera exposure used on this material.
  76468. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  76469. * This corresponds to a photographic exposure.
  76470. */
  76471. get: function () {
  76472. return this._imageProcessingConfiguration.exposure;
  76473. },
  76474. /**
  76475. * The camera exposure used on this material.
  76476. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  76477. * This corresponds to a photographic exposure.
  76478. */
  76479. set: function (value) {
  76480. this._imageProcessingConfiguration.exposure = value;
  76481. },
  76482. enumerable: true,
  76483. configurable: true
  76484. });
  76485. ;
  76486. ;
  76487. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  76488. /**
  76489. * Gets The camera contrast used on this material.
  76490. */
  76491. get: function () {
  76492. return this._imageProcessingConfiguration.contrast;
  76493. },
  76494. /**
  76495. * Sets The camera contrast used on this material.
  76496. */
  76497. set: function (value) {
  76498. this._imageProcessingConfiguration.contrast = value;
  76499. },
  76500. enumerable: true,
  76501. configurable: true
  76502. });
  76503. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  76504. /**
  76505. * Gets the Color Grading 2D Lookup Texture.
  76506. */
  76507. get: function () {
  76508. return this._imageProcessingConfiguration.colorGradingTexture;
  76509. },
  76510. /**
  76511. * Sets the Color Grading 2D Lookup Texture.
  76512. */
  76513. set: function (value) {
  76514. this.imageProcessingConfiguration.colorGradingTexture = value;
  76515. },
  76516. enumerable: true,
  76517. configurable: true
  76518. });
  76519. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  76520. /**
  76521. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  76522. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  76523. * 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;
  76524. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  76525. */
  76526. get: function () {
  76527. return this.imageProcessingConfiguration.colorCurves;
  76528. },
  76529. /**
  76530. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  76531. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  76532. * 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;
  76533. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  76534. */
  76535. set: function (value) {
  76536. this.imageProcessingConfiguration.colorCurves = value;
  76537. },
  76538. enumerable: true,
  76539. configurable: true
  76540. });
  76541. /**
  76542. * The entire material has been created in order to prevent overdraw.
  76543. * @returns false
  76544. */
  76545. BackgroundMaterial.prototype.needAlphaTesting = function () {
  76546. return true;
  76547. };
  76548. /**
  76549. * The entire material has been created in order to prevent overdraw.
  76550. * @returns true if blending is enable
  76551. */
  76552. BackgroundMaterial.prototype.needAlphaBlending = function () {
  76553. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  76554. };
  76555. /**
  76556. * Checks wether the material is ready to be rendered for a given mesh.
  76557. * @param mesh The mesh to render
  76558. * @param subMesh The submesh to check against
  76559. * @param useInstances Specify wether or not the material is used with instances
  76560. */
  76561. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  76562. var _this = this;
  76563. if (useInstances === void 0) { useInstances = false; }
  76564. if (subMesh.effect && this.isFrozen) {
  76565. if (this._wasPreviouslyReady) {
  76566. return true;
  76567. }
  76568. }
  76569. if (!subMesh._materialDefines) {
  76570. subMesh._materialDefines = new BackgroundMaterialDefines();
  76571. }
  76572. var scene = this.getScene();
  76573. var defines = subMesh._materialDefines;
  76574. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  76575. if (defines._renderId === scene.getRenderId()) {
  76576. return true;
  76577. }
  76578. }
  76579. var engine = scene.getEngine();
  76580. // Lights
  76581. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  76582. defines._needNormals = true;
  76583. // Textures
  76584. if (defines._areTexturesDirty) {
  76585. defines._needUVs = false;
  76586. if (scene.texturesEnabled) {
  76587. if (scene.getEngine().getCaps().textureLOD) {
  76588. defines.TEXTURELODSUPPORT = true;
  76589. }
  76590. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  76591. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  76592. return false;
  76593. }
  76594. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  76595. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  76596. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  76597. defines.OPACITYFRESNEL = this._opacityFresnel;
  76598. }
  76599. else {
  76600. defines.DIFFUSE = false;
  76601. defines.DIFFUSEHASALPHA = false;
  76602. defines.GAMMADIFFUSE = false;
  76603. defines.OPACITYFRESNEL = false;
  76604. }
  76605. var reflectionTexture = this._reflectionTexture;
  76606. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  76607. if (!reflectionTexture.isReadyOrNotBlocking()) {
  76608. return false;
  76609. }
  76610. defines.REFLECTION = true;
  76611. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  76612. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  76613. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  76614. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  76615. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  76616. defines.INVERTCUBICMAP = true;
  76617. }
  76618. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  76619. switch (reflectionTexture.coordinatesMode) {
  76620. case BABYLON.Texture.CUBIC_MODE:
  76621. case BABYLON.Texture.INVCUBIC_MODE:
  76622. defines.REFLECTIONMAP_CUBIC = true;
  76623. break;
  76624. case BABYLON.Texture.EXPLICIT_MODE:
  76625. defines.REFLECTIONMAP_EXPLICIT = true;
  76626. break;
  76627. case BABYLON.Texture.PLANAR_MODE:
  76628. defines.REFLECTIONMAP_PLANAR = true;
  76629. break;
  76630. case BABYLON.Texture.PROJECTION_MODE:
  76631. defines.REFLECTIONMAP_PROJECTION = true;
  76632. break;
  76633. case BABYLON.Texture.SKYBOX_MODE:
  76634. defines.REFLECTIONMAP_SKYBOX = true;
  76635. break;
  76636. case BABYLON.Texture.SPHERICAL_MODE:
  76637. defines.REFLECTIONMAP_SPHERICAL = true;
  76638. break;
  76639. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  76640. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  76641. break;
  76642. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  76643. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  76644. break;
  76645. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  76646. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  76647. break;
  76648. }
  76649. if (this.reflectionFresnel) {
  76650. defines.REFLECTIONFRESNEL = true;
  76651. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  76652. this._reflectionControls.x = this.reflectionAmount;
  76653. this._reflectionControls.y = this.reflectionReflectance0;
  76654. this._reflectionControls.z = this.reflectionReflectance90;
  76655. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  76656. }
  76657. else {
  76658. defines.REFLECTIONFRESNEL = false;
  76659. defines.REFLECTIONFALLOFF = false;
  76660. }
  76661. }
  76662. else {
  76663. defines.REFLECTION = false;
  76664. defines.REFLECTIONFALLOFF = false;
  76665. defines.REFLECTIONBLUR = false;
  76666. defines.REFLECTIONMAP_3D = false;
  76667. defines.REFLECTIONMAP_SPHERICAL = false;
  76668. defines.REFLECTIONMAP_PLANAR = false;
  76669. defines.REFLECTIONMAP_CUBIC = false;
  76670. defines.REFLECTIONMAP_PROJECTION = false;
  76671. defines.REFLECTIONMAP_SKYBOX = false;
  76672. defines.REFLECTIONMAP_EXPLICIT = false;
  76673. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  76674. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  76675. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  76676. defines.INVERTCUBICMAP = false;
  76677. defines.REFLECTIONMAP_OPPOSITEZ = false;
  76678. defines.LODINREFLECTIONALPHA = false;
  76679. defines.GAMMAREFLECTION = false;
  76680. }
  76681. }
  76682. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  76683. defines.USERGBCOLOR = this._useRGBColor;
  76684. defines.NOISE = this._enableNoise;
  76685. }
  76686. if (defines._areImageProcessingDirty) {
  76687. if (!this._imageProcessingConfiguration.isReady()) {
  76688. return false;
  76689. }
  76690. this._imageProcessingConfiguration.prepareDefines(defines);
  76691. }
  76692. // Misc.
  76693. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  76694. // Values that need to be evaluated on every frame
  76695. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, false);
  76696. // Attribs
  76697. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  76698. if (mesh) {
  76699. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  76700. mesh.createNormals(true);
  76701. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  76702. }
  76703. }
  76704. }
  76705. // Get correct effect
  76706. if (defines.isDirty) {
  76707. defines.markAsProcessed();
  76708. scene.resetCachedMaterial();
  76709. // Fallbacks
  76710. var fallbacks = new BABYLON.EffectFallbacks();
  76711. if (defines.FOG) {
  76712. fallbacks.addFallback(0, "FOG");
  76713. }
  76714. if (defines.POINTSIZE) {
  76715. fallbacks.addFallback(1, "POINTSIZE");
  76716. }
  76717. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  76718. if (defines.NUM_BONE_INFLUENCERS > 0) {
  76719. fallbacks.addCPUSkinningFallback(0, mesh);
  76720. }
  76721. //Attributes
  76722. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76723. if (defines.NORMAL) {
  76724. attribs.push(BABYLON.VertexBuffer.NormalKind);
  76725. }
  76726. if (defines.UV1) {
  76727. attribs.push(BABYLON.VertexBuffer.UVKind);
  76728. }
  76729. if (defines.UV2) {
  76730. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76731. }
  76732. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  76733. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  76734. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  76735. "vFogInfos", "vFogColor", "pointSize",
  76736. "vClipPlane", "mBones",
  76737. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  76738. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  76739. "shadowLevel", "alpha",
  76740. "vBackgroundCenter", "vReflectionControl",
  76741. "vDiffuseInfos", "diffuseMatrix",
  76742. ];
  76743. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  76744. var uniformBuffers = ["Material", "Scene"];
  76745. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  76746. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  76747. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  76748. uniformsNames: uniforms,
  76749. uniformBuffersNames: uniformBuffers,
  76750. samplers: samplers,
  76751. defines: defines,
  76752. maxSimultaneousLights: this._maxSimultaneousLights
  76753. });
  76754. var onCompiled = function (effect) {
  76755. if (_this.onCompiled) {
  76756. _this.onCompiled(effect);
  76757. }
  76758. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  76759. };
  76760. var join = defines.toString();
  76761. subMesh.setEffect(scene.getEngine().createEffect("background", {
  76762. attributes: attribs,
  76763. uniformsNames: uniforms,
  76764. uniformBuffersNames: uniformBuffers,
  76765. samplers: samplers,
  76766. defines: join,
  76767. fallbacks: fallbacks,
  76768. onCompiled: onCompiled,
  76769. onError: this.onError,
  76770. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  76771. }, engine), defines);
  76772. this.buildUniformLayout();
  76773. }
  76774. if (!subMesh.effect || !subMesh.effect.isReady()) {
  76775. return false;
  76776. }
  76777. defines._renderId = scene.getRenderId();
  76778. this._wasPreviouslyReady = true;
  76779. return true;
  76780. };
  76781. /**
  76782. * Build the uniform buffer used in the material.
  76783. */
  76784. BackgroundMaterial.prototype.buildUniformLayout = function () {
  76785. // Order is important !
  76786. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  76787. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  76788. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  76789. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  76790. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  76791. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  76792. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  76793. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  76794. this._uniformBuffer.addUniform("pointSize", 1);
  76795. this._uniformBuffer.addUniform("shadowLevel", 1);
  76796. this._uniformBuffer.addUniform("alpha", 1);
  76797. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  76798. this._uniformBuffer.addUniform("vReflectionControl", 4);
  76799. this._uniformBuffer.create();
  76800. };
  76801. /**
  76802. * Unbind the material.
  76803. */
  76804. BackgroundMaterial.prototype.unbind = function () {
  76805. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  76806. this._uniformBuffer.setTexture("diffuseSampler", null);
  76807. }
  76808. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  76809. this._uniformBuffer.setTexture("reflectionSampler", null);
  76810. }
  76811. _super.prototype.unbind.call(this);
  76812. };
  76813. /**
  76814. * Bind only the world matrix to the material.
  76815. * @param world The world matrix to bind.
  76816. */
  76817. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  76818. this._activeEffect.setMatrix("world", world);
  76819. };
  76820. /**
  76821. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  76822. * @param world The world matrix to bind.
  76823. * @param subMesh The submesh to bind for.
  76824. */
  76825. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  76826. var scene = this.getScene();
  76827. var defines = subMesh._materialDefines;
  76828. if (!defines) {
  76829. return;
  76830. }
  76831. var effect = subMesh.effect;
  76832. if (!effect) {
  76833. return;
  76834. }
  76835. this._activeEffect = effect;
  76836. // Matrices
  76837. this.bindOnlyWorldMatrix(world);
  76838. // Bones
  76839. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  76840. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  76841. if (mustRebind) {
  76842. this._uniformBuffer.bindToEffect(effect, "Material");
  76843. this.bindViewProjection(effect);
  76844. var reflectionTexture = this._reflectionTexture;
  76845. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  76846. // Texture uniforms
  76847. if (scene.texturesEnabled) {
  76848. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  76849. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  76850. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  76851. }
  76852. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  76853. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  76854. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  76855. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  76856. }
  76857. }
  76858. if (this.shadowLevel > 0) {
  76859. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  76860. }
  76861. this._uniformBuffer.updateFloat("alpha", this.alpha);
  76862. // Point size
  76863. if (this.pointsCloud) {
  76864. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  76865. }
  76866. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  76867. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  76868. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  76869. }
  76870. // Textures
  76871. if (scene.texturesEnabled) {
  76872. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  76873. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  76874. }
  76875. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  76876. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  76877. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  76878. }
  76879. else if (!defines.REFLECTIONBLUR) {
  76880. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  76881. }
  76882. else {
  76883. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  76884. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  76885. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  76886. }
  76887. if (defines.REFLECTIONFRESNEL) {
  76888. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  76889. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  76890. }
  76891. }
  76892. }
  76893. // Clip plane
  76894. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  76895. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  76896. }
  76897. if (mustRebind || !this.isFrozen) {
  76898. if (scene.lightsEnabled) {
  76899. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  76900. }
  76901. // View
  76902. this.bindView(effect);
  76903. // Fog
  76904. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  76905. // image processing
  76906. this._imageProcessingConfiguration.bind(this._activeEffect);
  76907. }
  76908. this._uniformBuffer.update();
  76909. this._afterBind(mesh);
  76910. };
  76911. /**
  76912. * Dispose the material.
  76913. * @forceDisposeEffect Force disposal of the associated effect.
  76914. * @forceDisposeTextures Force disposal of the associated textures.
  76915. */
  76916. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  76917. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  76918. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  76919. if (forceDisposeTextures) {
  76920. if (this.diffuseTexture) {
  76921. this.diffuseTexture.dispose();
  76922. }
  76923. if (this.reflectionTexture) {
  76924. this.reflectionTexture.dispose();
  76925. }
  76926. }
  76927. this._renderTargets.dispose();
  76928. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  76929. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  76930. }
  76931. _super.prototype.dispose.call(this, forceDisposeEffect);
  76932. };
  76933. /**
  76934. * Clones the material.
  76935. * @name The cloned name.
  76936. * @returns The cloned material.
  76937. */
  76938. BackgroundMaterial.prototype.clone = function (name) {
  76939. var _this = this;
  76940. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  76941. };
  76942. /**
  76943. * Serializes the current material to its JSON representation.
  76944. * @returns The JSON representation.
  76945. */
  76946. BackgroundMaterial.prototype.serialize = function () {
  76947. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76948. serializationObject.customType = "BABYLON.BackgroundMaterial";
  76949. return serializationObject;
  76950. };
  76951. /**
  76952. * Gets the class name of the material
  76953. * @returns "BackgroundMaterial"
  76954. */
  76955. BackgroundMaterial.prototype.getClassName = function () {
  76956. return "BackgroundMaterial";
  76957. };
  76958. /**
  76959. * Parse a JSON input to create back a background material.
  76960. * @param source
  76961. * @param scene
  76962. * @param rootUrl
  76963. * @returns the instantiated BackgroundMaterial.
  76964. */
  76965. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  76966. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  76967. };
  76968. /**
  76969. * Standard reflectance value at parallel view angle.
  76970. */
  76971. BackgroundMaterial.standardReflectance0 = 0.05;
  76972. /**
  76973. * Standard reflectance value at grazing angle.
  76974. */
  76975. BackgroundMaterial.standardReflectance90 = 0.5;
  76976. __decorate([
  76977. BABYLON.serializeAsColor3()
  76978. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  76979. __decorate([
  76980. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  76981. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  76982. __decorate([
  76983. BABYLON.serialize()
  76984. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  76985. __decorate([
  76986. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  76987. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  76988. __decorate([
  76989. BABYLON.serializeAsColor3()
  76990. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  76991. __decorate([
  76992. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  76993. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  76994. __decorate([
  76995. BABYLON.serialize()
  76996. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  76997. __decorate([
  76998. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  76999. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  77000. __decorate([
  77001. BABYLON.serializeAsColor3()
  77002. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  77003. __decorate([
  77004. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  77005. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  77006. __decorate([
  77007. BABYLON.serialize()
  77008. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  77009. __decorate([
  77010. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  77011. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  77012. __decorate([
  77013. BABYLON.serializeAsTexture()
  77014. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  77015. __decorate([
  77016. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77017. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  77018. __decorate([
  77019. BABYLON.serialize()
  77020. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  77021. __decorate([
  77022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77023. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  77024. __decorate([
  77025. BABYLON.serializeAsTexture()
  77026. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  77027. __decorate([
  77028. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77029. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  77030. __decorate([
  77031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77032. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  77033. __decorate([
  77034. BABYLON.serialize()
  77035. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  77036. __decorate([
  77037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77038. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  77039. __decorate([
  77040. BABYLON.serialize()
  77041. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  77042. __decorate([
  77043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77044. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  77045. __decorate([
  77046. BABYLON.serializeAsVector3()
  77047. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  77048. __decorate([
  77049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77050. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  77051. __decorate([
  77052. BABYLON.serialize()
  77053. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  77054. __decorate([
  77055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77056. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  77057. __decorate([
  77058. BABYLON.serialize()
  77059. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  77060. __decorate([
  77061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77062. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  77063. __decorate([
  77064. BABYLON.serialize()
  77065. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  77066. __decorate([
  77067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77068. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  77069. __decorate([
  77070. BABYLON.serialize()
  77071. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  77072. __decorate([
  77073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77074. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  77075. __decorate([
  77076. BABYLON.serialize()
  77077. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  77078. __decorate([
  77079. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77080. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  77081. __decorate([
  77082. BABYLON.serialize()
  77083. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  77084. __decorate([
  77085. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77086. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  77087. __decorate([
  77088. BABYLON.serialize()
  77089. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  77090. __decorate([
  77091. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77092. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  77093. __decorate([
  77094. BABYLON.serialize()
  77095. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  77096. __decorate([
  77097. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77098. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  77099. __decorate([
  77100. BABYLON.serialize()
  77101. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  77102. __decorate([
  77103. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77104. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  77105. __decorate([
  77106. BABYLON.serializeAsImageProcessingConfiguration()
  77107. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  77108. return BackgroundMaterial;
  77109. }(BABYLON.PushMaterial));
  77110. BABYLON.BackgroundMaterial = BackgroundMaterial;
  77111. })(BABYLON || (BABYLON = {}));
  77112. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  77113. var __assign = (this && this.__assign) || Object.assign || function(t) {
  77114. for (var s, i = 1, n = arguments.length; i < n; i++) {
  77115. s = arguments[i];
  77116. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  77117. t[p] = s[p];
  77118. }
  77119. return t;
  77120. };
  77121. var BABYLON;
  77122. (function (BABYLON) {
  77123. /**
  77124. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  77125. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  77126. * It also helps with the default setup of your imageProcessing configuration.
  77127. */
  77128. var EnvironmentHelper = /** @class */ (function () {
  77129. /**
  77130. * constructor
  77131. * @param options
  77132. * @param scene The scene to add the material to
  77133. */
  77134. function EnvironmentHelper(options, scene) {
  77135. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  77136. this._scene = scene;
  77137. this._setupBackground();
  77138. this._setupImageProcessing();
  77139. }
  77140. /**
  77141. * Creates the default options for the helper.
  77142. */
  77143. EnvironmentHelper._getDefaultOptions = function () {
  77144. return {
  77145. createGround: true,
  77146. groundSize: 15,
  77147. groundTexture: this._groundTextureCDNUrl,
  77148. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  77149. groundOpacity: 0.9,
  77150. enableGroundShadow: true,
  77151. groundShadowLevel: 0.5,
  77152. enableGroundMirror: false,
  77153. groundMirrorSizeRatio: 0.3,
  77154. groundMirrorBlurKernel: 64,
  77155. groundMirrorAmount: 1,
  77156. groundMirrorFresnelWeight: 1,
  77157. groundMirrorFallOffDistance: 0,
  77158. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  77159. createSkybox: true,
  77160. skyboxSize: 20,
  77161. skyboxTexture: this._skyboxTextureCDNUrl,
  77162. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  77163. backgroundYRotation: 0,
  77164. sizeAuto: true,
  77165. rootPosition: BABYLON.Vector3.Zero(),
  77166. setupImageProcessing: true,
  77167. environmentTexture: this._environmentTextureCDNUrl,
  77168. cameraExposure: 0.8,
  77169. cameraContrast: 1.2,
  77170. toneMappingEnabled: true,
  77171. };
  77172. };
  77173. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  77174. /**
  77175. * Gets the root mesh created by the helper.
  77176. */
  77177. get: function () {
  77178. return this._rootMesh;
  77179. },
  77180. enumerable: true,
  77181. configurable: true
  77182. });
  77183. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  77184. /**
  77185. * Gets the skybox created by the helper.
  77186. */
  77187. get: function () {
  77188. return this._skybox;
  77189. },
  77190. enumerable: true,
  77191. configurable: true
  77192. });
  77193. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  77194. /**
  77195. * Gets the skybox texture created by the helper.
  77196. */
  77197. get: function () {
  77198. return this._skyboxTexture;
  77199. },
  77200. enumerable: true,
  77201. configurable: true
  77202. });
  77203. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  77204. /**
  77205. * Gets the skybox material created by the helper.
  77206. */
  77207. get: function () {
  77208. return this._skyboxMaterial;
  77209. },
  77210. enumerable: true,
  77211. configurable: true
  77212. });
  77213. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  77214. /**
  77215. * Gets the ground mesh created by the helper.
  77216. */
  77217. get: function () {
  77218. return this._ground;
  77219. },
  77220. enumerable: true,
  77221. configurable: true
  77222. });
  77223. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  77224. /**
  77225. * Gets the ground texture created by the helper.
  77226. */
  77227. get: function () {
  77228. return this._groundTexture;
  77229. },
  77230. enumerable: true,
  77231. configurable: true
  77232. });
  77233. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  77234. /**
  77235. * Gets the ground mirror created by the helper.
  77236. */
  77237. get: function () {
  77238. return this._groundMirror;
  77239. },
  77240. enumerable: true,
  77241. configurable: true
  77242. });
  77243. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  77244. /**
  77245. * Gets the ground mirror render list to helps pushing the meshes
  77246. * you wish in the ground reflection.
  77247. */
  77248. get: function () {
  77249. if (this._groundMirror) {
  77250. return this._groundMirror.renderList;
  77251. }
  77252. return null;
  77253. },
  77254. enumerable: true,
  77255. configurable: true
  77256. });
  77257. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  77258. /**
  77259. * Gets the ground material created by the helper.
  77260. */
  77261. get: function () {
  77262. return this._groundMaterial;
  77263. },
  77264. enumerable: true,
  77265. configurable: true
  77266. });
  77267. /**
  77268. * Updates the background according to the new options
  77269. * @param options
  77270. */
  77271. EnvironmentHelper.prototype.updateOptions = function (options) {
  77272. var newOptions = __assign({}, this._options, options);
  77273. if (this._ground && !newOptions.createGround) {
  77274. this._ground.dispose();
  77275. this._ground = null;
  77276. }
  77277. if (this._groundMaterial && !newOptions.createGround) {
  77278. this._groundMaterial.dispose();
  77279. this._groundMaterial = null;
  77280. }
  77281. if (this._options.groundTexture && !newOptions.groundTexture && this._groundTexture) {
  77282. this._groundTexture.dispose();
  77283. this._groundTexture = null;
  77284. }
  77285. if (this._skybox && !newOptions.createSkybox) {
  77286. this._skybox.dispose();
  77287. this._skybox = null;
  77288. }
  77289. if (this._skyboxMaterial && !newOptions.createSkybox) {
  77290. this._skyboxMaterial.dispose();
  77291. this._skyboxMaterial = null;
  77292. }
  77293. if (this._options.skyboxTexture && !newOptions.skyboxTexture && this._skyboxTexture) {
  77294. this._skyboxTexture.dispose();
  77295. this._skyboxTexture = null;
  77296. }
  77297. if (this._groundMirror && !newOptions.enableGroundMirror) {
  77298. this._groundMirror.dispose();
  77299. this._groundMirror = null;
  77300. }
  77301. if (this._options.environmentTexture && !newOptions.environmentTexture && this._scene.environmentTexture) {
  77302. this._scene.environmentTexture.dispose();
  77303. }
  77304. this._options = newOptions;
  77305. this._setupBackground();
  77306. this._setupImageProcessing();
  77307. };
  77308. /**
  77309. * Sets the primary color of all the available elements.
  77310. * @param color
  77311. */
  77312. EnvironmentHelper.prototype.setMainColor = function (color) {
  77313. if (this.groundMaterial) {
  77314. this.groundMaterial.primaryColor = color;
  77315. }
  77316. if (this.skyboxMaterial) {
  77317. this.skyboxMaterial.primaryColor = color;
  77318. }
  77319. if (this.groundMirror) {
  77320. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  77321. }
  77322. };
  77323. /**
  77324. * Setup the image processing according to the specified options.
  77325. */
  77326. EnvironmentHelper.prototype._setupImageProcessing = function () {
  77327. if (this._options.setupImageProcessing) {
  77328. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  77329. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  77330. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  77331. this._setupEnvironmentTexture();
  77332. }
  77333. };
  77334. /**
  77335. * Setup the environment texture according to the specified options.
  77336. */
  77337. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  77338. if (this._scene.environmentTexture) {
  77339. return;
  77340. }
  77341. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  77342. this._scene.environmentTexture = this._options.environmentTexture;
  77343. return;
  77344. }
  77345. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  77346. this._scene.environmentTexture = environmentTexture;
  77347. };
  77348. /**
  77349. * Setup the background according to the specified options.
  77350. */
  77351. EnvironmentHelper.prototype._setupBackground = function () {
  77352. if (!this._rootMesh) {
  77353. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  77354. }
  77355. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  77356. var sceneSize = this._getSceneSize();
  77357. if (this._options.createGround) {
  77358. this._setupGround(sceneSize);
  77359. this._setupGroundMaterial();
  77360. this._setupGroundDiffuseTexture();
  77361. if (this._options.enableGroundMirror) {
  77362. this._setupGroundMirrorTexture(sceneSize);
  77363. }
  77364. this._setupMirrorInGroundMaterial();
  77365. }
  77366. if (this._options.createSkybox) {
  77367. this._setupSkybox(sceneSize);
  77368. this._setupSkyboxMaterial();
  77369. this._setupSkyboxReflectionTexture();
  77370. }
  77371. this._rootMesh.position.x = sceneSize.rootPosition.x;
  77372. this._rootMesh.position.z = sceneSize.rootPosition.z;
  77373. this._rootMesh.position.y = sceneSize.rootPosition.y;
  77374. };
  77375. /**
  77376. * Get the scene sizes according to the setup.
  77377. */
  77378. EnvironmentHelper.prototype._getSceneSize = function () {
  77379. var groundSize = this._options.groundSize;
  77380. var skyboxSize = this._options.skyboxSize;
  77381. var rootPosition = this._options.rootPosition;
  77382. var sceneExtends = this._scene.getWorldExtends();
  77383. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  77384. var bias = 0.0001;
  77385. if (this._options.sizeAuto) {
  77386. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  77387. this._scene.activeCamera.upperRadiusLimit) {
  77388. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  77389. }
  77390. if (this._scene.activeCamera) {
  77391. bias = (this._scene.activeCamera.maxZ - this._scene.activeCamera.minZ) / 10000;
  77392. }
  77393. var sceneDiagonalLenght = sceneDiagonal.length();
  77394. if (sceneDiagonalLenght > groundSize) {
  77395. groundSize = sceneDiagonalLenght * 2;
  77396. }
  77397. // 10 % bigger.
  77398. groundSize *= 1.1;
  77399. skyboxSize *= 1.5;
  77400. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  77401. rootPosition.y = sceneExtends.min.y - bias;
  77402. }
  77403. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  77404. };
  77405. /**
  77406. * Setup the ground according to the specified options.
  77407. */
  77408. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  77409. if (!this._ground) {
  77410. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  77411. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  77412. this._ground.parent = this._rootMesh;
  77413. }
  77414. this._ground.receiveShadows = this._options.enableGroundShadow;
  77415. };
  77416. /**
  77417. * Setup the ground material according to the specified options.
  77418. */
  77419. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  77420. if (!this._groundMaterial) {
  77421. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  77422. }
  77423. this._groundMaterial.alpha = this._options.groundOpacity;
  77424. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  77425. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  77426. this._groundMaterial.primaryLevel = 1;
  77427. this._groundMaterial.primaryColor = this._options.groundColor;
  77428. this._groundMaterial.secondaryLevel = 0;
  77429. this._groundMaterial.tertiaryLevel = 0;
  77430. this._groundMaterial.useRGBColor = false;
  77431. this._groundMaterial.enableNoise = true;
  77432. if (this._ground) {
  77433. this._ground.material = this._groundMaterial;
  77434. }
  77435. };
  77436. /**
  77437. * Setup the ground diffuse texture according to the specified options.
  77438. */
  77439. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  77440. if (!this._groundMaterial) {
  77441. return;
  77442. }
  77443. if (this._groundTexture) {
  77444. return;
  77445. }
  77446. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  77447. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  77448. return;
  77449. }
  77450. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  77451. diffuseTexture.gammaSpace = false;
  77452. diffuseTexture.hasAlpha = true;
  77453. this._groundMaterial.diffuseTexture = diffuseTexture;
  77454. };
  77455. /**
  77456. * Setup the ground mirror texture according to the specified options.
  77457. */
  77458. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  77459. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77460. if (!this._groundMirror) {
  77461. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  77462. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  77463. this._groundMirror.anisotropicFilteringLevel = 1;
  77464. this._groundMirror.wrapU = wrapping;
  77465. this._groundMirror.wrapV = wrapping;
  77466. this._groundMirror.gammaSpace = false;
  77467. if (this._groundMirror.renderList) {
  77468. for (var i = 0; i < this._scene.meshes.length; i++) {
  77469. var mesh = this._scene.meshes[i];
  77470. if (mesh !== this._ground &&
  77471. mesh !== this._skybox &&
  77472. mesh !== this._rootMesh) {
  77473. this._groundMirror.renderList.push(mesh);
  77474. }
  77475. }
  77476. }
  77477. }
  77478. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  77479. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  77480. };
  77481. /**
  77482. * Setup the ground to receive the mirror texture.
  77483. */
  77484. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  77485. if (this._groundMaterial) {
  77486. this._groundMaterial.reflectionTexture = this._groundMirror;
  77487. this._groundMaterial.reflectionFresnel = true;
  77488. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  77489. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  77490. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  77491. }
  77492. };
  77493. /**
  77494. * Setup the skybox according to the specified options.
  77495. */
  77496. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  77497. if (!this._skybox) {
  77498. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  77499. }
  77500. this._skybox.parent = this._rootMesh;
  77501. };
  77502. /**
  77503. * Setup the skybox material according to the specified options.
  77504. */
  77505. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  77506. if (!this._skybox) {
  77507. return;
  77508. }
  77509. if (!this._skyboxMaterial) {
  77510. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  77511. }
  77512. this._skyboxMaterial.useRGBColor = false;
  77513. this._skyboxMaterial.primaryLevel = 1;
  77514. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  77515. this._skyboxMaterial.secondaryLevel = 0;
  77516. this._skyboxMaterial.tertiaryLevel = 0;
  77517. this._skyboxMaterial.enableNoise = true;
  77518. this._skybox.material = this._skyboxMaterial;
  77519. };
  77520. /**
  77521. * Setup the skybox reflection texture according to the specified options.
  77522. */
  77523. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  77524. if (!this._skyboxMaterial) {
  77525. return;
  77526. }
  77527. if (this._skyboxTexture) {
  77528. return;
  77529. }
  77530. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  77531. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  77532. return;
  77533. }
  77534. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  77535. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  77536. this._skyboxTexture.gammaSpace = false;
  77537. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  77538. };
  77539. /**
  77540. * Dispose all the elements created by the Helper.
  77541. */
  77542. EnvironmentHelper.prototype.dispose = function () {
  77543. if (this._groundMaterial) {
  77544. this._groundMaterial.dispose(true, true);
  77545. }
  77546. if (this._skyboxMaterial) {
  77547. this._skyboxMaterial.dispose(true, true);
  77548. }
  77549. this._rootMesh.dispose(true);
  77550. };
  77551. /**
  77552. * Default ground texture URL.
  77553. */
  77554. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  77555. /**
  77556. * Default skybox texture URL.
  77557. */
  77558. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  77559. /**
  77560. * Default environment texture URL.
  77561. */
  77562. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  77563. return EnvironmentHelper;
  77564. }());
  77565. BABYLON.EnvironmentHelper = EnvironmentHelper;
  77566. })(BABYLON || (BABYLON = {}));
  77567. //# sourceMappingURL=babylon.environmentHelper.js.map
  77568. 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;\nfloat opacity0=opacityPerceptual*opacityPerceptual;\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(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=abs(texture2D(textureSampler,vUV).r);\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,1.0);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","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}"};
  77569. 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.rgb+=mix(-0.5/255.0,0.5/255.0,rand);\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};"};
  77570. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  77571. var BABYLON;
  77572. (function (BABYLON) {
  77573. var GridMaterialDefines = /** @class */ (function (_super) {
  77574. __extends(GridMaterialDefines, _super);
  77575. function GridMaterialDefines() {
  77576. var _this = _super.call(this) || this;
  77577. _this.TRANSPARENT = false;
  77578. _this.FOG = false;
  77579. _this.PREMULTIPLYALPHA = false;
  77580. _this.rebuild();
  77581. return _this;
  77582. }
  77583. return GridMaterialDefines;
  77584. }(BABYLON.MaterialDefines));
  77585. /**
  77586. * The grid materials allows you to wrap any shape with a grid.
  77587. * Colors are customizable.
  77588. */
  77589. var GridMaterial = /** @class */ (function (_super) {
  77590. __extends(GridMaterial, _super);
  77591. /**
  77592. * constructor
  77593. * @param name The name given to the material in order to identify it afterwards.
  77594. * @param scene The scene the material is used in.
  77595. */
  77596. function GridMaterial(name, scene) {
  77597. var _this = _super.call(this, name, scene) || this;
  77598. /**
  77599. * Main color of the grid (e.g. between lines)
  77600. */
  77601. _this.mainColor = BABYLON.Color3.Black();
  77602. /**
  77603. * Color of the grid lines.
  77604. */
  77605. _this.lineColor = BABYLON.Color3.Teal();
  77606. /**
  77607. * The scale of the grid compared to unit.
  77608. */
  77609. _this.gridRatio = 1.0;
  77610. /**
  77611. * Allows setting an offset for the grid lines.
  77612. */
  77613. _this.gridOffset = BABYLON.Vector3.Zero();
  77614. /**
  77615. * The frequency of thicker lines.
  77616. */
  77617. _this.majorUnitFrequency = 10;
  77618. /**
  77619. * The visibility of minor units in the grid.
  77620. */
  77621. _this.minorUnitVisibility = 0.33;
  77622. /**
  77623. * The grid opacity outside of the lines.
  77624. */
  77625. _this.opacity = 1.0;
  77626. /**
  77627. * Determine RBG output is premultiplied by alpha value.
  77628. */
  77629. _this.preMultiplyAlpha = false;
  77630. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  77631. return _this;
  77632. }
  77633. /**
  77634. * Returns wehter or not the grid requires alpha blending.
  77635. */
  77636. GridMaterial.prototype.needAlphaBlending = function () {
  77637. return this.opacity < 1.0;
  77638. };
  77639. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  77640. return this.needAlphaBlending();
  77641. };
  77642. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  77643. if (this.isFrozen) {
  77644. if (this._wasPreviouslyReady && subMesh.effect) {
  77645. return true;
  77646. }
  77647. }
  77648. if (!subMesh._materialDefines) {
  77649. subMesh._materialDefines = new GridMaterialDefines();
  77650. }
  77651. var defines = subMesh._materialDefines;
  77652. var scene = this.getScene();
  77653. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  77654. if (this._renderId === scene.getRenderId()) {
  77655. return true;
  77656. }
  77657. }
  77658. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  77659. defines.TRANSPARENT = !defines.TRANSPARENT;
  77660. defines.markAsUnprocessed();
  77661. }
  77662. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  77663. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  77664. defines.markAsUnprocessed();
  77665. }
  77666. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  77667. // Get correct effect
  77668. if (defines.isDirty) {
  77669. defines.markAsProcessed();
  77670. scene.resetCachedMaterial();
  77671. // Attributes
  77672. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  77673. // Defines
  77674. var join = defines.toString();
  77675. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  77676. }
  77677. if (!subMesh.effect || !subMesh.effect.isReady()) {
  77678. return false;
  77679. }
  77680. this._renderId = scene.getRenderId();
  77681. this._wasPreviouslyReady = true;
  77682. return true;
  77683. };
  77684. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  77685. var scene = this.getScene();
  77686. var defines = subMesh._materialDefines;
  77687. if (!defines) {
  77688. return;
  77689. }
  77690. var effect = subMesh.effect;
  77691. if (!effect) {
  77692. return;
  77693. }
  77694. this._activeEffect = effect;
  77695. // Matrices
  77696. this.bindOnlyWorldMatrix(world);
  77697. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  77698. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  77699. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  77700. // Uniforms
  77701. if (this._mustRebind(scene, effect)) {
  77702. this._activeEffect.setColor3("mainColor", this.mainColor);
  77703. this._activeEffect.setColor3("lineColor", this.lineColor);
  77704. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  77705. this._gridControl.x = this.gridRatio;
  77706. this._gridControl.y = Math.round(this.majorUnitFrequency);
  77707. this._gridControl.z = this.minorUnitVisibility;
  77708. this._gridControl.w = this.opacity;
  77709. this._activeEffect.setVector4("gridControl", this._gridControl);
  77710. }
  77711. // Fog
  77712. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  77713. this._afterBind(mesh, this._activeEffect);
  77714. };
  77715. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  77716. _super.prototype.dispose.call(this, forceDisposeEffect);
  77717. };
  77718. GridMaterial.prototype.clone = function (name) {
  77719. var _this = this;
  77720. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  77721. };
  77722. GridMaterial.prototype.serialize = function () {
  77723. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  77724. serializationObject.customType = "BABYLON.GridMaterial";
  77725. return serializationObject;
  77726. };
  77727. GridMaterial.prototype.getClassName = function () {
  77728. return "GridMaterial";
  77729. };
  77730. GridMaterial.Parse = function (source, scene, rootUrl) {
  77731. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  77732. };
  77733. __decorate([
  77734. BABYLON.serializeAsColor3()
  77735. ], GridMaterial.prototype, "mainColor", void 0);
  77736. __decorate([
  77737. BABYLON.serializeAsColor3()
  77738. ], GridMaterial.prototype, "lineColor", void 0);
  77739. __decorate([
  77740. BABYLON.serialize()
  77741. ], GridMaterial.prototype, "gridRatio", void 0);
  77742. __decorate([
  77743. BABYLON.serializeAsColor3()
  77744. ], GridMaterial.prototype, "gridOffset", void 0);
  77745. __decorate([
  77746. BABYLON.serialize()
  77747. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  77748. __decorate([
  77749. BABYLON.serialize()
  77750. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  77751. __decorate([
  77752. BABYLON.serialize()
  77753. ], GridMaterial.prototype, "opacity", void 0);
  77754. __decorate([
  77755. BABYLON.serialize()
  77756. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  77757. return GridMaterial;
  77758. }(BABYLON.PushMaterial));
  77759. BABYLON.GridMaterial = GridMaterial;
  77760. })(BABYLON || (BABYLON = {}));
  77761. //# sourceMappingURL=babylon.gridmaterial.js.map
  77762. 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}";
  77763. 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}";
  77764. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  77765. var BABYLON;
  77766. (function (BABYLON) {
  77767. var GLTFLoaderCoordinateSystemMode;
  77768. (function (GLTFLoaderCoordinateSystemMode) {
  77769. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  77770. // NOTE: When scene.useRightHandedSystem is false, an additional transform will be added to the root to transform the data from right-handed to left-handed.
  77771. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  77772. // The glTF right-handed data is not transformed in any form and is loaded directly.
  77773. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  77774. // Sets the useRightHandedSystem flag on the scene.
  77775. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  77776. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  77777. var GLTFFileLoader = /** @class */ (function () {
  77778. function GLTFFileLoader() {
  77779. // V2 options
  77780. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  77781. this.compileMaterials = false;
  77782. this.compileShadowGenerators = false;
  77783. this.useClipPlane = false;
  77784. this.name = "gltf";
  77785. this.extensions = {
  77786. ".gltf": { isBinary: false },
  77787. ".glb": { isBinary: true }
  77788. };
  77789. }
  77790. GLTFFileLoader.prototype.dispose = function () {
  77791. if (this._loader) {
  77792. this._loader.dispose();
  77793. }
  77794. };
  77795. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  77796. try {
  77797. var loaderData = GLTFFileLoader._parse(data);
  77798. if (this.onParsed) {
  77799. this.onParsed(loaderData);
  77800. }
  77801. this._loader = this._getLoader(loaderData);
  77802. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  77803. }
  77804. catch (e) {
  77805. onError(e.message);
  77806. }
  77807. };
  77808. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  77809. try {
  77810. var loaderData = GLTFFileLoader._parse(data);
  77811. if (this.onParsed) {
  77812. this.onParsed(loaderData);
  77813. }
  77814. this._loader = this._getLoader(loaderData);
  77815. this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  77816. }
  77817. catch (e) {
  77818. onError(e.message);
  77819. }
  77820. };
  77821. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  77822. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  77823. };
  77824. GLTFFileLoader.prototype.createPlugin = function () {
  77825. return new GLTFFileLoader();
  77826. };
  77827. GLTFFileLoader._parse = function (data) {
  77828. if (data instanceof ArrayBuffer) {
  77829. return GLTFFileLoader._parseBinary(data);
  77830. }
  77831. return {
  77832. json: JSON.parse(data),
  77833. bin: null
  77834. };
  77835. };
  77836. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  77837. var loaderVersion = { major: 2, minor: 0 };
  77838. var asset = loaderData.json.asset || {};
  77839. var version = GLTFFileLoader._parseVersion(asset.version);
  77840. if (!version) {
  77841. throw new Error("Invalid version: " + asset.version);
  77842. }
  77843. if (asset.minVersion !== undefined) {
  77844. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  77845. if (!minVersion) {
  77846. throw new Error("Invalid minimum version: " + asset.minVersion);
  77847. }
  77848. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  77849. throw new Error("Incompatible minimum version: " + asset.minVersion);
  77850. }
  77851. }
  77852. var createLoaders = {
  77853. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  77854. 2: GLTFFileLoader.CreateGLTFLoaderV2
  77855. };
  77856. var createLoader = createLoaders[version.major];
  77857. if (!createLoader) {
  77858. throw new Error("Unsupported version: " + asset.version);
  77859. }
  77860. return createLoader(this);
  77861. };
  77862. GLTFFileLoader._parseBinary = function (data) {
  77863. var Binary = {
  77864. Magic: 0x46546C67
  77865. };
  77866. var binaryReader = new BinaryReader(data);
  77867. var magic = binaryReader.readUint32();
  77868. if (magic !== Binary.Magic) {
  77869. throw new Error("Unexpected magic: " + magic);
  77870. }
  77871. var version = binaryReader.readUint32();
  77872. switch (version) {
  77873. case 1: return GLTFFileLoader._parseV1(binaryReader);
  77874. case 2: return GLTFFileLoader._parseV2(binaryReader);
  77875. }
  77876. throw new Error("Unsupported version: " + version);
  77877. };
  77878. GLTFFileLoader._parseV1 = function (binaryReader) {
  77879. var ContentFormat = {
  77880. JSON: 0
  77881. };
  77882. var length = binaryReader.readUint32();
  77883. if (length != binaryReader.getLength()) {
  77884. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  77885. }
  77886. var contentLength = binaryReader.readUint32();
  77887. var contentFormat = binaryReader.readUint32();
  77888. var content;
  77889. switch (contentFormat) {
  77890. case ContentFormat.JSON: {
  77891. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  77892. break;
  77893. }
  77894. default: {
  77895. throw new Error("Unexpected content format: " + contentFormat);
  77896. }
  77897. }
  77898. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  77899. var body = binaryReader.readUint8Array(bytesRemaining);
  77900. return {
  77901. json: content,
  77902. bin: body
  77903. };
  77904. };
  77905. GLTFFileLoader._parseV2 = function (binaryReader) {
  77906. var ChunkFormat = {
  77907. JSON: 0x4E4F534A,
  77908. BIN: 0x004E4942
  77909. };
  77910. var length = binaryReader.readUint32();
  77911. if (length !== binaryReader.getLength()) {
  77912. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  77913. }
  77914. // JSON chunk
  77915. var chunkLength = binaryReader.readUint32();
  77916. var chunkFormat = binaryReader.readUint32();
  77917. if (chunkFormat !== ChunkFormat.JSON) {
  77918. throw new Error("First chunk format is not JSON");
  77919. }
  77920. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  77921. // Look for BIN chunk
  77922. var bin = null;
  77923. while (binaryReader.getPosition() < binaryReader.getLength()) {
  77924. var chunkLength_1 = binaryReader.readUint32();
  77925. var chunkFormat_1 = binaryReader.readUint32();
  77926. switch (chunkFormat_1) {
  77927. case ChunkFormat.JSON: {
  77928. throw new Error("Unexpected JSON chunk");
  77929. }
  77930. case ChunkFormat.BIN: {
  77931. bin = binaryReader.readUint8Array(chunkLength_1);
  77932. break;
  77933. }
  77934. default: {
  77935. // ignore unrecognized chunkFormat
  77936. binaryReader.skipBytes(chunkLength_1);
  77937. break;
  77938. }
  77939. }
  77940. }
  77941. return {
  77942. json: json,
  77943. bin: bin
  77944. };
  77945. };
  77946. GLTFFileLoader._parseVersion = function (version) {
  77947. var match = (version + "").match(/^(\d+)\.(\d+)$/);
  77948. if (!match) {
  77949. return null;
  77950. }
  77951. return {
  77952. major: parseInt(match[1]),
  77953. minor: parseInt(match[2])
  77954. };
  77955. };
  77956. GLTFFileLoader._compareVersion = function (a, b) {
  77957. if (a.major > b.major)
  77958. return 1;
  77959. if (a.major < b.major)
  77960. return -1;
  77961. if (a.minor > b.minor)
  77962. return 1;
  77963. if (a.minor < b.minor)
  77964. return -1;
  77965. return 0;
  77966. };
  77967. GLTFFileLoader._decodeBufferToText = function (buffer) {
  77968. var result = "";
  77969. var length = buffer.byteLength;
  77970. for (var i = 0; i < length; i++) {
  77971. result += String.fromCharCode(buffer[i]);
  77972. }
  77973. return result;
  77974. };
  77975. // V1 options
  77976. GLTFFileLoader.HomogeneousCoordinates = false;
  77977. GLTFFileLoader.IncrementalLoading = true;
  77978. return GLTFFileLoader;
  77979. }());
  77980. BABYLON.GLTFFileLoader = GLTFFileLoader;
  77981. var BinaryReader = /** @class */ (function () {
  77982. function BinaryReader(arrayBuffer) {
  77983. this._arrayBuffer = arrayBuffer;
  77984. this._dataView = new DataView(arrayBuffer);
  77985. this._byteOffset = 0;
  77986. }
  77987. BinaryReader.prototype.getPosition = function () {
  77988. return this._byteOffset;
  77989. };
  77990. BinaryReader.prototype.getLength = function () {
  77991. return this._arrayBuffer.byteLength;
  77992. };
  77993. BinaryReader.prototype.readUint32 = function () {
  77994. var value = this._dataView.getUint32(this._byteOffset, true);
  77995. this._byteOffset += 4;
  77996. return value;
  77997. };
  77998. BinaryReader.prototype.readUint8Array = function (length) {
  77999. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  78000. this._byteOffset += length;
  78001. return value;
  78002. };
  78003. BinaryReader.prototype.skipBytes = function (length) {
  78004. this._byteOffset += length;
  78005. };
  78006. return BinaryReader;
  78007. }());
  78008. if (BABYLON.SceneLoader) {
  78009. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  78010. }
  78011. })(BABYLON || (BABYLON = {}));
  78012. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  78013. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  78014. var BABYLON;
  78015. (function (BABYLON) {
  78016. var GLTF1;
  78017. (function (GLTF1) {
  78018. /**
  78019. * Enums
  78020. */
  78021. var EComponentType;
  78022. (function (EComponentType) {
  78023. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  78024. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  78025. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  78026. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  78027. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  78028. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  78029. var EShaderType;
  78030. (function (EShaderType) {
  78031. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  78032. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  78033. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  78034. var EParameterType;
  78035. (function (EParameterType) {
  78036. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  78037. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  78038. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  78039. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  78040. EParameterType[EParameterType["INT"] = 5124] = "INT";
  78041. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  78042. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  78043. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  78044. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  78045. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  78046. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  78047. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  78048. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  78049. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  78050. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  78051. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  78052. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  78053. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  78054. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  78055. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  78056. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  78057. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  78058. var ETextureWrapMode;
  78059. (function (ETextureWrapMode) {
  78060. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  78061. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  78062. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  78063. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  78064. var ETextureFilterType;
  78065. (function (ETextureFilterType) {
  78066. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  78067. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  78068. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  78069. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  78070. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  78071. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  78072. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  78073. var ETextureFormat;
  78074. (function (ETextureFormat) {
  78075. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  78076. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  78077. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  78078. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  78079. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  78080. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  78081. var ECullingType;
  78082. (function (ECullingType) {
  78083. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  78084. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  78085. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  78086. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  78087. var EBlendingFunction;
  78088. (function (EBlendingFunction) {
  78089. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  78090. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  78091. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  78092. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  78093. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  78094. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  78095. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  78096. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  78097. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  78098. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  78099. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  78100. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  78101. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  78102. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  78103. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  78104. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  78105. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  78106. })(BABYLON || (BABYLON = {}));
  78107. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  78108. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  78109. var BABYLON;
  78110. (function (BABYLON) {
  78111. var GLTF1;
  78112. (function (GLTF1) {
  78113. /**
  78114. * Tokenizer. Used for shaders compatibility
  78115. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  78116. */
  78117. var ETokenType;
  78118. (function (ETokenType) {
  78119. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  78120. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  78121. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  78122. })(ETokenType || (ETokenType = {}));
  78123. var Tokenizer = /** @class */ (function () {
  78124. function Tokenizer(toParse) {
  78125. this._pos = 0;
  78126. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  78127. this._toParse = toParse;
  78128. this._maxPos = toParse.length;
  78129. }
  78130. Tokenizer.prototype.getNextToken = function () {
  78131. if (this.isEnd())
  78132. return ETokenType.END_OF_INPUT;
  78133. this.currentString = this.read();
  78134. this.currentToken = ETokenType.UNKNOWN;
  78135. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  78136. this.currentToken = ETokenType.IDENTIFIER;
  78137. this.currentIdentifier = this.currentString;
  78138. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  78139. this.currentIdentifier += this.currentString;
  78140. this.forward();
  78141. }
  78142. }
  78143. return this.currentToken;
  78144. };
  78145. Tokenizer.prototype.peek = function () {
  78146. return this._toParse[this._pos];
  78147. };
  78148. Tokenizer.prototype.read = function () {
  78149. return this._toParse[this._pos++];
  78150. };
  78151. Tokenizer.prototype.forward = function () {
  78152. this._pos++;
  78153. };
  78154. Tokenizer.prototype.isEnd = function () {
  78155. return this._pos >= this._maxPos;
  78156. };
  78157. return Tokenizer;
  78158. }());
  78159. /**
  78160. * Values
  78161. */
  78162. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  78163. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  78164. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  78165. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  78166. /**
  78167. * Parse
  78168. */
  78169. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  78170. for (var buf in parsedBuffers) {
  78171. var parsedBuffer = parsedBuffers[buf];
  78172. gltfRuntime.buffers[buf] = parsedBuffer;
  78173. gltfRuntime.buffersCount++;
  78174. }
  78175. };
  78176. var parseShaders = function (parsedShaders, gltfRuntime) {
  78177. for (var sha in parsedShaders) {
  78178. var parsedShader = parsedShaders[sha];
  78179. gltfRuntime.shaders[sha] = parsedShader;
  78180. gltfRuntime.shaderscount++;
  78181. }
  78182. };
  78183. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  78184. for (var object in parsedObjects) {
  78185. var parsedObject = parsedObjects[object];
  78186. gltfRuntime[runtimeProperty][object] = parsedObject;
  78187. }
  78188. };
  78189. /**
  78190. * Utils
  78191. */
  78192. var normalizeUVs = function (buffer) {
  78193. if (!buffer) {
  78194. return;
  78195. }
  78196. for (var i = 0; i < buffer.length / 2; i++) {
  78197. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  78198. }
  78199. };
  78200. var getAttribute = function (attributeParameter) {
  78201. if (attributeParameter.semantic === "NORMAL") {
  78202. return "normal";
  78203. }
  78204. else if (attributeParameter.semantic === "POSITION") {
  78205. return "position";
  78206. }
  78207. else if (attributeParameter.semantic === "JOINT") {
  78208. return "matricesIndices";
  78209. }
  78210. else if (attributeParameter.semantic === "WEIGHT") {
  78211. return "matricesWeights";
  78212. }
  78213. else if (attributeParameter.semantic === "COLOR") {
  78214. return "color";
  78215. }
  78216. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  78217. var channel = Number(attributeParameter.semantic.split("_")[1]);
  78218. return "uv" + (channel === 0 ? "" : channel + 1);
  78219. }
  78220. return null;
  78221. };
  78222. /**
  78223. * Loads and creates animations
  78224. */
  78225. var loadAnimations = function (gltfRuntime) {
  78226. for (var anim in gltfRuntime.animations) {
  78227. var animation = gltfRuntime.animations[anim];
  78228. if (!animation.channels || !animation.samplers) {
  78229. continue;
  78230. }
  78231. var lastAnimation = null;
  78232. for (var i = 0; i < animation.channels.length; i++) {
  78233. // Get parameters and load buffers
  78234. var channel = animation.channels[i];
  78235. var sampler = animation.samplers[channel.sampler];
  78236. if (!sampler) {
  78237. continue;
  78238. }
  78239. var inputData = null;
  78240. var outputData = null;
  78241. if (animation.parameters) {
  78242. inputData = animation.parameters[sampler.input];
  78243. outputData = animation.parameters[sampler.output];
  78244. }
  78245. else {
  78246. inputData = sampler.input;
  78247. outputData = sampler.output;
  78248. }
  78249. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  78250. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  78251. var targetID = channel.target.id;
  78252. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  78253. if (targetNode === null) {
  78254. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  78255. }
  78256. if (targetNode === null) {
  78257. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  78258. continue;
  78259. }
  78260. var isBone = targetNode instanceof BABYLON.Bone;
  78261. // Get target path (position, rotation or scaling)
  78262. var targetPath = channel.target.path;
  78263. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  78264. if (targetPathIndex !== -1) {
  78265. targetPath = babylonAnimationPaths[targetPathIndex];
  78266. }
  78267. // Determine animation type
  78268. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  78269. if (!isBone) {
  78270. if (targetPath === "rotationQuaternion") {
  78271. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  78272. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  78273. }
  78274. else {
  78275. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  78276. }
  78277. }
  78278. // Create animation and key frames
  78279. var babylonAnimation = null;
  78280. var keys = [];
  78281. var arrayOffset = 0;
  78282. var modifyKey = false;
  78283. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  78284. babylonAnimation = lastAnimation;
  78285. modifyKey = true;
  78286. }
  78287. if (!modifyKey) {
  78288. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  78289. }
  78290. // For each frame
  78291. for (var j = 0; j < bufferInput.length; j++) {
  78292. var value = null;
  78293. if (targetPath === "rotationQuaternion") {
  78294. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  78295. arrayOffset += 4;
  78296. }
  78297. else {
  78298. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  78299. arrayOffset += 3;
  78300. }
  78301. if (isBone) {
  78302. var bone = targetNode;
  78303. var translation = BABYLON.Vector3.Zero();
  78304. var rotationQuaternion = new BABYLON.Quaternion();
  78305. var scaling = BABYLON.Vector3.Zero();
  78306. // Warning on decompose
  78307. var mat = bone.getBaseMatrix();
  78308. if (modifyKey && lastAnimation) {
  78309. mat = lastAnimation.getKeys()[j].value;
  78310. }
  78311. mat.decompose(scaling, rotationQuaternion, translation);
  78312. if (targetPath === "position") {
  78313. translation = value;
  78314. }
  78315. else if (targetPath === "rotationQuaternion") {
  78316. rotationQuaternion = value;
  78317. }
  78318. else {
  78319. scaling = value;
  78320. }
  78321. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  78322. }
  78323. if (!modifyKey) {
  78324. keys.push({
  78325. frame: bufferInput[j],
  78326. value: value
  78327. });
  78328. }
  78329. else if (lastAnimation) {
  78330. lastAnimation.getKeys()[j].value = value;
  78331. }
  78332. }
  78333. // Finish
  78334. if (!modifyKey && babylonAnimation) {
  78335. babylonAnimation.setKeys(keys);
  78336. targetNode.animations.push(babylonAnimation);
  78337. }
  78338. lastAnimation = babylonAnimation;
  78339. gltfRuntime.scene.stopAnimation(targetNode);
  78340. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  78341. }
  78342. }
  78343. };
  78344. /**
  78345. * Returns the bones transformation matrix
  78346. */
  78347. var configureBoneTransformation = function (node) {
  78348. var mat = null;
  78349. if (node.translation || node.rotation || node.scale) {
  78350. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  78351. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  78352. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  78353. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  78354. }
  78355. else {
  78356. mat = BABYLON.Matrix.FromArray(node.matrix);
  78357. }
  78358. return mat;
  78359. };
  78360. /**
  78361. * Returns the parent bone
  78362. */
  78363. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  78364. // Try to find
  78365. for (var i = 0; i < newSkeleton.bones.length; i++) {
  78366. if (newSkeleton.bones[i].name === jointName) {
  78367. return newSkeleton.bones[i];
  78368. }
  78369. }
  78370. // Not found, search in gltf nodes
  78371. var nodes = gltfRuntime.nodes;
  78372. for (var nde in nodes) {
  78373. var node = nodes[nde];
  78374. if (!node.jointName) {
  78375. continue;
  78376. }
  78377. var children = node.children;
  78378. for (var i = 0; i < children.length; i++) {
  78379. var child = gltfRuntime.nodes[children[i]];
  78380. if (!child.jointName) {
  78381. continue;
  78382. }
  78383. if (child.jointName === jointName) {
  78384. var mat = configureBoneTransformation(node);
  78385. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  78386. bone.id = nde;
  78387. return bone;
  78388. }
  78389. }
  78390. }
  78391. return null;
  78392. };
  78393. /**
  78394. * Returns the appropriate root node
  78395. */
  78396. var getNodeToRoot = function (nodesToRoot, id) {
  78397. for (var i = 0; i < nodesToRoot.length; i++) {
  78398. var nodeToRoot = nodesToRoot[i];
  78399. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  78400. var child = nodeToRoot.node.children[j];
  78401. if (child === id) {
  78402. return nodeToRoot.bone;
  78403. }
  78404. }
  78405. }
  78406. return null;
  78407. };
  78408. /**
  78409. * Returns the node with the joint name
  78410. */
  78411. var getJointNode = function (gltfRuntime, jointName) {
  78412. var nodes = gltfRuntime.nodes;
  78413. var node = nodes[jointName];
  78414. if (node) {
  78415. return {
  78416. node: node,
  78417. id: jointName
  78418. };
  78419. }
  78420. for (var nde in nodes) {
  78421. node = nodes[nde];
  78422. if (node.jointName === jointName) {
  78423. return {
  78424. node: node,
  78425. id: nde
  78426. };
  78427. }
  78428. }
  78429. return null;
  78430. };
  78431. /**
  78432. * Checks if a nodes is in joints
  78433. */
  78434. var nodeIsInJoints = function (skins, id) {
  78435. for (var i = 0; i < skins.jointNames.length; i++) {
  78436. if (skins.jointNames[i] === id) {
  78437. return true;
  78438. }
  78439. }
  78440. return false;
  78441. };
  78442. /**
  78443. * Fills the nodes to root for bones and builds hierarchy
  78444. */
  78445. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  78446. // Creates nodes for root
  78447. for (var nde in gltfRuntime.nodes) {
  78448. var node = gltfRuntime.nodes[nde];
  78449. var id = nde;
  78450. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  78451. continue;
  78452. }
  78453. // Create node to root bone
  78454. var mat = configureBoneTransformation(node);
  78455. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  78456. bone.id = id;
  78457. nodesToRoot.push({ bone: bone, node: node, id: id });
  78458. }
  78459. // Parenting
  78460. for (var i = 0; i < nodesToRoot.length; i++) {
  78461. var nodeToRoot = nodesToRoot[i];
  78462. var children = nodeToRoot.node.children;
  78463. for (var j = 0; j < children.length; j++) {
  78464. var child = null;
  78465. for (var k = 0; k < nodesToRoot.length; k++) {
  78466. if (nodesToRoot[k].id === children[j]) {
  78467. child = nodesToRoot[k];
  78468. break;
  78469. }
  78470. }
  78471. if (child) {
  78472. child.bone._parent = nodeToRoot.bone;
  78473. nodeToRoot.bone.children.push(child.bone);
  78474. }
  78475. }
  78476. }
  78477. };
  78478. /**
  78479. * Imports a skeleton
  78480. */
  78481. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  78482. if (!newSkeleton) {
  78483. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  78484. }
  78485. if (!skins.babylonSkeleton) {
  78486. return newSkeleton;
  78487. }
  78488. // Find the root bones
  78489. var nodesToRoot = [];
  78490. var nodesToRootToAdd = [];
  78491. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  78492. newSkeleton.bones = [];
  78493. // Joints
  78494. for (var i = 0; i < skins.jointNames.length; i++) {
  78495. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  78496. if (!jointNode) {
  78497. continue;
  78498. }
  78499. var node = jointNode.node;
  78500. if (!node) {
  78501. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  78502. continue;
  78503. }
  78504. var id = jointNode.id;
  78505. // Optimize, if the bone already exists...
  78506. var existingBone = gltfRuntime.scene.getBoneByID(id);
  78507. if (existingBone) {
  78508. newSkeleton.bones.push(existingBone);
  78509. continue;
  78510. }
  78511. // Search for parent bone
  78512. var foundBone = false;
  78513. var parentBone = null;
  78514. for (var j = 0; j < i; j++) {
  78515. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  78516. if (!jointNode_1) {
  78517. continue;
  78518. }
  78519. var joint = jointNode_1.node;
  78520. if (!joint) {
  78521. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  78522. continue;
  78523. }
  78524. var children = joint.children;
  78525. if (!children) {
  78526. continue;
  78527. }
  78528. foundBone = false;
  78529. for (var k = 0; k < children.length; k++) {
  78530. if (children[k] === id) {
  78531. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  78532. foundBone = true;
  78533. break;
  78534. }
  78535. }
  78536. if (foundBone) {
  78537. break;
  78538. }
  78539. }
  78540. // Create bone
  78541. var mat = configureBoneTransformation(node);
  78542. if (!parentBone && nodesToRoot.length > 0) {
  78543. parentBone = getNodeToRoot(nodesToRoot, id);
  78544. if (parentBone) {
  78545. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  78546. nodesToRootToAdd.push(parentBone);
  78547. }
  78548. }
  78549. }
  78550. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  78551. bone.id = id;
  78552. }
  78553. // Polish
  78554. var bones = newSkeleton.bones;
  78555. newSkeleton.bones = [];
  78556. for (var i = 0; i < skins.jointNames.length; i++) {
  78557. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  78558. if (!jointNode) {
  78559. continue;
  78560. }
  78561. for (var j = 0; j < bones.length; j++) {
  78562. if (bones[j].id === jointNode.id) {
  78563. newSkeleton.bones.push(bones[j]);
  78564. break;
  78565. }
  78566. }
  78567. }
  78568. newSkeleton.prepare();
  78569. // Finish
  78570. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  78571. newSkeleton.bones.push(nodesToRootToAdd[i]);
  78572. }
  78573. return newSkeleton;
  78574. };
  78575. /**
  78576. * Imports a mesh and its geometries
  78577. */
  78578. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  78579. if (!newMesh) {
  78580. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  78581. newMesh.id = id;
  78582. }
  78583. if (!node.babylonNode) {
  78584. return newMesh;
  78585. }
  78586. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  78587. if (!newMesh.material) {
  78588. newMesh.material = multiMat;
  78589. }
  78590. var vertexData = new BABYLON.VertexData();
  78591. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  78592. var verticesStarts = new Array();
  78593. var verticesCounts = new Array();
  78594. var indexStarts = new Array();
  78595. var indexCounts = new Array();
  78596. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  78597. var meshID = meshes[meshIndex];
  78598. var mesh = gltfRuntime.meshes[meshID];
  78599. if (!mesh) {
  78600. continue;
  78601. }
  78602. // Positions, normals and UVs
  78603. for (var i = 0; i < mesh.primitives.length; i++) {
  78604. // Temporary vertex data
  78605. var tempVertexData = new BABYLON.VertexData();
  78606. var primitive = mesh.primitives[i];
  78607. if (primitive.mode !== 4) {
  78608. // continue;
  78609. }
  78610. var attributes = primitive.attributes;
  78611. var accessor = null;
  78612. var buffer = null;
  78613. // Set positions, normal and uvs
  78614. for (var semantic in attributes) {
  78615. // Link accessor and buffer view
  78616. accessor = gltfRuntime.accessors[attributes[semantic]];
  78617. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  78618. if (semantic === "NORMAL") {
  78619. tempVertexData.normals = new Float32Array(buffer.length);
  78620. tempVertexData.normals.set(buffer);
  78621. }
  78622. else if (semantic === "POSITION") {
  78623. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  78624. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  78625. for (var j = 0; j < buffer.length; j += 4) {
  78626. tempVertexData.positions[j] = buffer[j];
  78627. tempVertexData.positions[j + 1] = buffer[j + 1];
  78628. tempVertexData.positions[j + 2] = buffer[j + 2];
  78629. }
  78630. }
  78631. else {
  78632. tempVertexData.positions = new Float32Array(buffer.length);
  78633. tempVertexData.positions.set(buffer);
  78634. }
  78635. verticesCounts.push(tempVertexData.positions.length);
  78636. }
  78637. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  78638. var channel = Number(semantic.split("_")[1]);
  78639. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  78640. var uvs = new Float32Array(buffer.length);
  78641. uvs.set(buffer);
  78642. normalizeUVs(uvs);
  78643. tempVertexData.set(uvs, uvKind);
  78644. }
  78645. else if (semantic === "JOINT") {
  78646. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  78647. tempVertexData.matricesIndices.set(buffer);
  78648. }
  78649. else if (semantic === "WEIGHT") {
  78650. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  78651. tempVertexData.matricesWeights.set(buffer);
  78652. }
  78653. else if (semantic === "COLOR") {
  78654. tempVertexData.colors = new Float32Array(buffer.length);
  78655. tempVertexData.colors.set(buffer);
  78656. }
  78657. }
  78658. // Indices
  78659. accessor = gltfRuntime.accessors[primitive.indices];
  78660. if (accessor) {
  78661. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  78662. tempVertexData.indices = new Int32Array(buffer.length);
  78663. tempVertexData.indices.set(buffer);
  78664. indexCounts.push(tempVertexData.indices.length);
  78665. }
  78666. else {
  78667. // Set indices on the fly
  78668. var indices = [];
  78669. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  78670. indices.push(j);
  78671. }
  78672. tempVertexData.indices = new Int32Array(indices);
  78673. indexCounts.push(tempVertexData.indices.length);
  78674. }
  78675. vertexData.merge(tempVertexData);
  78676. // Sub material
  78677. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  78678. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  78679. // Update vertices start and index start
  78680. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  78681. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  78682. }
  78683. }
  78684. // Apply geometry
  78685. geometry.setAllVerticesData(vertexData, false);
  78686. newMesh.computeWorldMatrix(true);
  78687. // Apply submeshes
  78688. newMesh.subMeshes = [];
  78689. var index = 0;
  78690. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  78691. var meshID = meshes[meshIndex];
  78692. var mesh = gltfRuntime.meshes[meshID];
  78693. if (!mesh) {
  78694. continue;
  78695. }
  78696. for (var i = 0; i < mesh.primitives.length; i++) {
  78697. if (mesh.primitives[i].mode !== 4) {
  78698. //continue;
  78699. }
  78700. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  78701. index++;
  78702. }
  78703. }
  78704. // Finish
  78705. return newMesh;
  78706. };
  78707. /**
  78708. * Configure node transformation from position, rotation and scaling
  78709. */
  78710. var configureNode = function (newNode, position, rotation, scaling) {
  78711. if (newNode.position) {
  78712. newNode.position = position;
  78713. }
  78714. if (newNode.rotationQuaternion || newNode.rotation) {
  78715. newNode.rotationQuaternion = rotation;
  78716. }
  78717. if (newNode.scaling) {
  78718. newNode.scaling = scaling;
  78719. }
  78720. };
  78721. /**
  78722. * Configures node from transformation matrix
  78723. */
  78724. var configureNodeFromMatrix = function (newNode, node, parent) {
  78725. if (node.matrix) {
  78726. var position = new BABYLON.Vector3(0, 0, 0);
  78727. var rotation = new BABYLON.Quaternion();
  78728. var scaling = new BABYLON.Vector3(0, 0, 0);
  78729. var mat = BABYLON.Matrix.FromArray(node.matrix);
  78730. mat.decompose(scaling, rotation, position);
  78731. configureNode(newNode, position, rotation, scaling);
  78732. }
  78733. else if (node.translation && node.rotation && node.scale) {
  78734. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  78735. }
  78736. newNode.computeWorldMatrix(true);
  78737. };
  78738. /**
  78739. * Imports a node
  78740. */
  78741. var importNode = function (gltfRuntime, node, id, parent) {
  78742. var lastNode = null;
  78743. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  78744. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  78745. return null;
  78746. }
  78747. }
  78748. // Meshes
  78749. if (node.skin) {
  78750. if (node.meshes) {
  78751. var skin = gltfRuntime.skins[node.skin];
  78752. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  78753. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  78754. if (newMesh.skeleton === null && skin.babylonSkeleton) {
  78755. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  78756. if (!skin.babylonSkeleton) {
  78757. skin.babylonSkeleton = newMesh.skeleton;
  78758. }
  78759. }
  78760. lastNode = newMesh;
  78761. }
  78762. }
  78763. else if (node.meshes) {
  78764. /**
  78765. * Improve meshes property
  78766. */
  78767. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  78768. lastNode = newMesh;
  78769. }
  78770. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  78771. var light = gltfRuntime.lights[node.light];
  78772. if (light) {
  78773. if (light.type === "ambient") {
  78774. var ambienLight = light[light.type];
  78775. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  78776. hemiLight.name = node.name || "";
  78777. if (ambienLight.color) {
  78778. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  78779. }
  78780. lastNode = hemiLight;
  78781. }
  78782. else if (light.type === "directional") {
  78783. var directionalLight = light[light.type];
  78784. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  78785. dirLight.name = node.name || "";
  78786. if (directionalLight.color) {
  78787. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  78788. }
  78789. lastNode = dirLight;
  78790. }
  78791. else if (light.type === "point") {
  78792. var pointLight = light[light.type];
  78793. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  78794. ptLight.name = node.name || "";
  78795. if (pointLight.color) {
  78796. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  78797. }
  78798. lastNode = ptLight;
  78799. }
  78800. else if (light.type === "spot") {
  78801. var spotLight = light[light.type];
  78802. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  78803. spLight.name = node.name || "";
  78804. if (spotLight.color) {
  78805. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  78806. }
  78807. if (spotLight.fallOfAngle) {
  78808. spLight.angle = spotLight.fallOfAngle;
  78809. }
  78810. if (spotLight.fallOffExponent) {
  78811. spLight.exponent = spotLight.fallOffExponent;
  78812. }
  78813. lastNode = spLight;
  78814. }
  78815. }
  78816. }
  78817. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  78818. var camera = gltfRuntime.cameras[node.camera];
  78819. if (camera) {
  78820. if (camera.type === "orthographic") {
  78821. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  78822. orthoCamera.name = node.name || "";
  78823. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  78824. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  78825. lastNode = orthoCamera;
  78826. }
  78827. else if (camera.type === "perspective") {
  78828. var perspectiveCamera = camera[camera.type];
  78829. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  78830. persCamera.name = node.name || "";
  78831. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  78832. if (!perspectiveCamera.aspectRatio) {
  78833. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  78834. }
  78835. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  78836. persCamera.maxZ = perspectiveCamera.zfar;
  78837. persCamera.minZ = perspectiveCamera.znear;
  78838. }
  78839. lastNode = persCamera;
  78840. }
  78841. }
  78842. }
  78843. // Empty node
  78844. if (!node.jointName) {
  78845. if (node.babylonNode) {
  78846. return node.babylonNode;
  78847. }
  78848. else if (lastNode === null) {
  78849. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  78850. node.babylonNode = dummy;
  78851. lastNode = dummy;
  78852. }
  78853. }
  78854. if (lastNode !== null) {
  78855. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  78856. configureNodeFromMatrix(lastNode, node, parent);
  78857. }
  78858. else {
  78859. var translation = node.translation || [0, 0, 0];
  78860. var rotation = node.rotation || [0, 0, 0, 1];
  78861. var scale = node.scale || [1, 1, 1];
  78862. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  78863. }
  78864. lastNode.updateCache(true);
  78865. node.babylonNode = lastNode;
  78866. }
  78867. return lastNode;
  78868. };
  78869. /**
  78870. * Traverses nodes and creates them
  78871. */
  78872. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  78873. if (meshIncluded === void 0) { meshIncluded = false; }
  78874. var node = gltfRuntime.nodes[id];
  78875. var newNode = null;
  78876. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  78877. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  78878. meshIncluded = true;
  78879. }
  78880. else {
  78881. meshIncluded = false;
  78882. }
  78883. }
  78884. else {
  78885. meshIncluded = true;
  78886. }
  78887. if (!node.jointName && meshIncluded) {
  78888. newNode = importNode(gltfRuntime, node, id, parent);
  78889. if (newNode !== null) {
  78890. newNode.id = id;
  78891. newNode.parent = parent;
  78892. }
  78893. }
  78894. if (node.children) {
  78895. for (var i = 0; i < node.children.length; i++) {
  78896. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  78897. }
  78898. }
  78899. };
  78900. /**
  78901. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  78902. */
  78903. var postLoad = function (gltfRuntime) {
  78904. // Nodes
  78905. var currentScene = gltfRuntime.currentScene;
  78906. if (currentScene) {
  78907. for (var i = 0; i < currentScene.nodes.length; i++) {
  78908. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  78909. }
  78910. }
  78911. else {
  78912. for (var thing in gltfRuntime.scenes) {
  78913. currentScene = gltfRuntime.scenes[thing];
  78914. for (var i = 0; i < currentScene.nodes.length; i++) {
  78915. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  78916. }
  78917. }
  78918. }
  78919. // Set animations
  78920. loadAnimations(gltfRuntime);
  78921. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  78922. var skeleton = gltfRuntime.scene.skeletons[i];
  78923. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  78924. }
  78925. };
  78926. /**
  78927. * onBind shaderrs callback to set uniforms and matrices
  78928. */
  78929. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  78930. var materialValues = material.values || technique.parameters;
  78931. for (var unif in unTreatedUniforms) {
  78932. var uniform = unTreatedUniforms[unif];
  78933. var type = uniform.type;
  78934. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  78935. if (uniform.semantic && !uniform.source && !uniform.node) {
  78936. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  78937. }
  78938. else if (uniform.semantic && (uniform.source || uniform.node)) {
  78939. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  78940. if (source === null) {
  78941. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  78942. }
  78943. if (source === null) {
  78944. continue;
  78945. }
  78946. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  78947. }
  78948. }
  78949. else {
  78950. var value = materialValues[technique.uniforms[unif]];
  78951. if (!value) {
  78952. continue;
  78953. }
  78954. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  78955. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  78956. if (texture === null || texture === undefined) {
  78957. continue;
  78958. }
  78959. shaderMaterial.getEffect().setTexture(unif, texture);
  78960. }
  78961. else {
  78962. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  78963. }
  78964. }
  78965. }
  78966. onSuccess(shaderMaterial);
  78967. };
  78968. /**
  78969. * Prepare uniforms to send the only one time
  78970. * Loads the appropriate textures
  78971. */
  78972. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  78973. var materialValues = material.values || technique.parameters;
  78974. var techniqueUniforms = technique.uniforms;
  78975. /**
  78976. * Prepare values here (not matrices)
  78977. */
  78978. for (var unif in unTreatedUniforms) {
  78979. var uniform = unTreatedUniforms[unif];
  78980. var type = uniform.type;
  78981. var value = materialValues[techniqueUniforms[unif]];
  78982. if (value === undefined) {
  78983. // In case the value is the same for all materials
  78984. value = uniform.value;
  78985. }
  78986. if (!value) {
  78987. continue;
  78988. }
  78989. var onLoadTexture = function (uniformName) {
  78990. return function (texture) {
  78991. if (uniform.value && uniformName) {
  78992. // Static uniform
  78993. shaderMaterial.setTexture(uniformName, texture);
  78994. delete unTreatedUniforms[uniformName];
  78995. }
  78996. };
  78997. };
  78998. // Texture (sampler2D)
  78999. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  79000. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  79001. }
  79002. else {
  79003. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  79004. // Static uniform
  79005. delete unTreatedUniforms[unif];
  79006. }
  79007. }
  79008. }
  79009. };
  79010. /**
  79011. * Shader compilation failed
  79012. */
  79013. var onShaderCompileError = function (program, shaderMaterial, onError) {
  79014. return function (effect, error) {
  79015. shaderMaterial.dispose(true);
  79016. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  79017. };
  79018. };
  79019. /**
  79020. * Shader compilation success
  79021. */
  79022. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  79023. return function (_) {
  79024. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  79025. shaderMaterial.onBind = function (mesh) {
  79026. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  79027. };
  79028. };
  79029. };
  79030. /**
  79031. * Returns the appropriate uniform if already handled by babylon
  79032. */
  79033. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  79034. for (var unif in technique.uniforms) {
  79035. var uniform = technique.uniforms[unif];
  79036. var uniformParameter = technique.parameters[uniform];
  79037. if (tokenizer.currentIdentifier === unif) {
  79038. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  79039. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  79040. if (transformIndex !== -1) {
  79041. delete unTreatedUniforms[unif];
  79042. return babylonTransforms[transformIndex];
  79043. }
  79044. }
  79045. }
  79046. }
  79047. return tokenizer.currentIdentifier;
  79048. };
  79049. /**
  79050. * All shaders loaded. Create materials one by one
  79051. */
  79052. var importMaterials = function (gltfRuntime) {
  79053. // Create materials
  79054. for (var mat in gltfRuntime.materials) {
  79055. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  79056. }
  79057. };
  79058. /**
  79059. * Implementation of the base glTF spec
  79060. */
  79061. var GLTFLoaderBase = /** @class */ (function () {
  79062. function GLTFLoaderBase() {
  79063. }
  79064. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  79065. var gltfRuntime = {
  79066. extensions: {},
  79067. accessors: {},
  79068. buffers: {},
  79069. bufferViews: {},
  79070. meshes: {},
  79071. lights: {},
  79072. cameras: {},
  79073. nodes: {},
  79074. images: {},
  79075. textures: {},
  79076. shaders: {},
  79077. programs: {},
  79078. samplers: {},
  79079. techniques: {},
  79080. materials: {},
  79081. animations: {},
  79082. skins: {},
  79083. extensionsUsed: [],
  79084. scenes: {},
  79085. buffersCount: 0,
  79086. shaderscount: 0,
  79087. scene: scene,
  79088. rootUrl: rootUrl,
  79089. loadedBufferCount: 0,
  79090. loadedBufferViews: {},
  79091. loadedShaderCount: 0,
  79092. importOnlyMeshes: false,
  79093. dummyNodes: []
  79094. };
  79095. // Parse
  79096. if (parsedData.extensions) {
  79097. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  79098. }
  79099. if (parsedData.extensionsUsed) {
  79100. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  79101. }
  79102. if (parsedData.buffers) {
  79103. parseBuffers(parsedData.buffers, gltfRuntime);
  79104. }
  79105. if (parsedData.bufferViews) {
  79106. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  79107. }
  79108. if (parsedData.accessors) {
  79109. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  79110. }
  79111. if (parsedData.meshes) {
  79112. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  79113. }
  79114. if (parsedData.lights) {
  79115. parseObject(parsedData.lights, "lights", gltfRuntime);
  79116. }
  79117. if (parsedData.cameras) {
  79118. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  79119. }
  79120. if (parsedData.nodes) {
  79121. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  79122. }
  79123. if (parsedData.images) {
  79124. parseObject(parsedData.images, "images", gltfRuntime);
  79125. }
  79126. if (parsedData.textures) {
  79127. parseObject(parsedData.textures, "textures", gltfRuntime);
  79128. }
  79129. if (parsedData.shaders) {
  79130. parseShaders(parsedData.shaders, gltfRuntime);
  79131. }
  79132. if (parsedData.programs) {
  79133. parseObject(parsedData.programs, "programs", gltfRuntime);
  79134. }
  79135. if (parsedData.samplers) {
  79136. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  79137. }
  79138. if (parsedData.techniques) {
  79139. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  79140. }
  79141. if (parsedData.materials) {
  79142. parseObject(parsedData.materials, "materials", gltfRuntime);
  79143. }
  79144. if (parsedData.animations) {
  79145. parseObject(parsedData.animations, "animations", gltfRuntime);
  79146. }
  79147. if (parsedData.skins) {
  79148. parseObject(parsedData.skins, "skins", gltfRuntime);
  79149. }
  79150. if (parsedData.scenes) {
  79151. gltfRuntime.scenes = parsedData.scenes;
  79152. }
  79153. if (parsedData.scene && parsedData.scenes) {
  79154. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  79155. }
  79156. return gltfRuntime;
  79157. };
  79158. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  79159. var buffer = gltfRuntime.buffers[id];
  79160. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  79161. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  79162. }
  79163. else {
  79164. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  79165. if (request) {
  79166. onError(request.status + " " + request.statusText);
  79167. }
  79168. });
  79169. }
  79170. };
  79171. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  79172. var texture = gltfRuntime.textures[id];
  79173. if (!texture || !texture.source) {
  79174. onError("");
  79175. return;
  79176. }
  79177. if (texture.babylonTexture) {
  79178. onSuccess(null);
  79179. return;
  79180. }
  79181. var source = gltfRuntime.images[texture.source];
  79182. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  79183. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  79184. }
  79185. else {
  79186. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  79187. if (request) {
  79188. onError(request.status + " " + request.statusText);
  79189. }
  79190. });
  79191. }
  79192. };
  79193. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  79194. var texture = gltfRuntime.textures[id];
  79195. if (texture.babylonTexture) {
  79196. onSuccess(texture.babylonTexture);
  79197. return;
  79198. }
  79199. var sampler = gltfRuntime.samplers[texture.sampler];
  79200. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  79201. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  79202. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  79203. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  79204. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  79205. var blob = new Blob([buffer]);
  79206. var blobURL = URL.createObjectURL(blob);
  79207. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  79208. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  79209. if (sampler.wrapS !== undefined) {
  79210. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  79211. }
  79212. if (sampler.wrapT !== undefined) {
  79213. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  79214. }
  79215. newTexture.name = id;
  79216. texture.babylonTexture = newTexture;
  79217. onSuccess(newTexture);
  79218. };
  79219. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  79220. var shader = gltfRuntime.shaders[id];
  79221. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  79222. var shaderString = atob(shader.uri.split(",")[1]);
  79223. onSuccess(shaderString);
  79224. }
  79225. else {
  79226. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  79227. if (request) {
  79228. onError(request.status + " " + request.statusText);
  79229. }
  79230. });
  79231. }
  79232. };
  79233. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  79234. var material = gltfRuntime.materials[id];
  79235. if (!material.technique) {
  79236. if (onError) {
  79237. onError("No technique found.");
  79238. }
  79239. return;
  79240. }
  79241. var technique = gltfRuntime.techniques[material.technique];
  79242. if (!technique) {
  79243. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  79244. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  79245. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  79246. onSuccess(defaultMaterial);
  79247. return;
  79248. }
  79249. var program = gltfRuntime.programs[technique.program];
  79250. var states = technique.states;
  79251. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  79252. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  79253. var newVertexShader = "";
  79254. var newPixelShader = "";
  79255. var vertexTokenizer = new Tokenizer(vertexShader);
  79256. var pixelTokenizer = new Tokenizer(pixelShader);
  79257. var unTreatedUniforms = {};
  79258. var uniforms = [];
  79259. var attributes = [];
  79260. var samplers = [];
  79261. // Fill uniform, sampler2D and attributes
  79262. for (var unif in technique.uniforms) {
  79263. var uniform = technique.uniforms[unif];
  79264. var uniformParameter = technique.parameters[uniform];
  79265. unTreatedUniforms[unif] = uniformParameter;
  79266. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  79267. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  79268. if (transformIndex !== -1) {
  79269. uniforms.push(babylonTransforms[transformIndex]);
  79270. delete unTreatedUniforms[unif];
  79271. }
  79272. else {
  79273. uniforms.push(unif);
  79274. }
  79275. }
  79276. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  79277. samplers.push(unif);
  79278. }
  79279. else {
  79280. uniforms.push(unif);
  79281. }
  79282. }
  79283. for (var attr in technique.attributes) {
  79284. var attribute = technique.attributes[attr];
  79285. var attributeParameter = technique.parameters[attribute];
  79286. if (attributeParameter.semantic) {
  79287. attributes.push(getAttribute(attributeParameter));
  79288. }
  79289. }
  79290. // Configure vertex shader
  79291. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  79292. var tokenType = vertexTokenizer.currentToken;
  79293. if (tokenType !== ETokenType.IDENTIFIER) {
  79294. newVertexShader += vertexTokenizer.currentString;
  79295. continue;
  79296. }
  79297. var foundAttribute = false;
  79298. for (var attr in technique.attributes) {
  79299. var attribute = technique.attributes[attr];
  79300. var attributeParameter = technique.parameters[attribute];
  79301. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  79302. newVertexShader += getAttribute(attributeParameter);
  79303. foundAttribute = true;
  79304. break;
  79305. }
  79306. }
  79307. if (foundAttribute) {
  79308. continue;
  79309. }
  79310. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  79311. }
  79312. // Configure pixel shader
  79313. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  79314. var tokenType = pixelTokenizer.currentToken;
  79315. if (tokenType !== ETokenType.IDENTIFIER) {
  79316. newPixelShader += pixelTokenizer.currentString;
  79317. continue;
  79318. }
  79319. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  79320. }
  79321. // Create shader material
  79322. var shaderPath = {
  79323. vertex: program.vertexShader + id,
  79324. fragment: program.fragmentShader + id
  79325. };
  79326. var options = {
  79327. attributes: attributes,
  79328. uniforms: uniforms,
  79329. samplers: samplers,
  79330. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  79331. };
  79332. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  79333. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  79334. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  79335. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  79336. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  79337. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  79338. if (states && states.functions) {
  79339. var functions = states.functions;
  79340. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  79341. shaderMaterial.backFaceCulling = false;
  79342. }
  79343. var blendFunc = functions.blendFuncSeparate;
  79344. if (blendFunc) {
  79345. 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) {
  79346. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  79347. }
  79348. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  79349. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  79350. }
  79351. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  79352. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  79353. }
  79354. 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) {
  79355. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  79356. }
  79357. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  79358. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  79359. }
  79360. 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) {
  79361. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  79362. }
  79363. }
  79364. }
  79365. };
  79366. return GLTFLoaderBase;
  79367. }());
  79368. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  79369. /**
  79370. * glTF V1 Loader
  79371. */
  79372. var GLTFLoader = /** @class */ (function () {
  79373. function GLTFLoader() {
  79374. }
  79375. GLTFLoader.RegisterExtension = function (extension) {
  79376. if (GLTFLoader.Extensions[extension.name]) {
  79377. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  79378. return;
  79379. }
  79380. GLTFLoader.Extensions[extension.name] = extension;
  79381. };
  79382. GLTFLoader.prototype.dispose = function () {
  79383. // do nothing
  79384. };
  79385. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  79386. var _this = this;
  79387. scene.useRightHandedSystem = true;
  79388. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  79389. gltfRuntime.importOnlyMeshes = true;
  79390. if (meshesNames === "") {
  79391. gltfRuntime.importMeshesNames = [];
  79392. }
  79393. else if (typeof meshesNames === "string") {
  79394. gltfRuntime.importMeshesNames = [meshesNames];
  79395. }
  79396. else if (meshesNames && !(meshesNames instanceof Array)) {
  79397. gltfRuntime.importMeshesNames = [meshesNames];
  79398. }
  79399. else {
  79400. gltfRuntime.importMeshesNames = [];
  79401. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  79402. }
  79403. // Create nodes
  79404. _this._createNodes(gltfRuntime);
  79405. var meshes = new Array();
  79406. var skeletons = new Array();
  79407. // Fill arrays of meshes and skeletons
  79408. for (var nde in gltfRuntime.nodes) {
  79409. var node = gltfRuntime.nodes[nde];
  79410. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  79411. meshes.push(node.babylonNode);
  79412. }
  79413. }
  79414. for (var skl in gltfRuntime.skins) {
  79415. var skin = gltfRuntime.skins[skl];
  79416. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  79417. skeletons.push(skin.babylonSkeleton);
  79418. }
  79419. }
  79420. // Load buffers, shaders, materials, etc.
  79421. _this._loadBuffersAsync(gltfRuntime, function () {
  79422. _this._loadShadersAsync(gltfRuntime, function () {
  79423. importMaterials(gltfRuntime);
  79424. postLoad(gltfRuntime);
  79425. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  79426. onSuccess(meshes, [], skeletons);
  79427. }
  79428. });
  79429. }, onProgress);
  79430. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  79431. onSuccess(meshes, [], skeletons);
  79432. }
  79433. }, onError);
  79434. return true;
  79435. };
  79436. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  79437. var _this = this;
  79438. scene.useRightHandedSystem = true;
  79439. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  79440. // Load runtime extensios
  79441. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  79442. // Create nodes
  79443. _this._createNodes(gltfRuntime);
  79444. // Load buffers, shaders, materials, etc.
  79445. _this._loadBuffersAsync(gltfRuntime, function () {
  79446. _this._loadShadersAsync(gltfRuntime, function () {
  79447. importMaterials(gltfRuntime);
  79448. postLoad(gltfRuntime);
  79449. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  79450. onSuccess();
  79451. }
  79452. });
  79453. });
  79454. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  79455. onSuccess();
  79456. }
  79457. }, onError);
  79458. }, onError);
  79459. };
  79460. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  79461. var hasShaders = false;
  79462. var processShader = function (sha, shader) {
  79463. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  79464. gltfRuntime.loadedShaderCount++;
  79465. if (shaderString) {
  79466. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  79467. }
  79468. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  79469. onload();
  79470. }
  79471. }, function () {
  79472. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  79473. });
  79474. };
  79475. for (var sha in gltfRuntime.shaders) {
  79476. hasShaders = true;
  79477. var shader = gltfRuntime.shaders[sha];
  79478. if (shader) {
  79479. processShader.bind(this, sha, shader)();
  79480. }
  79481. else {
  79482. BABYLON.Tools.Error("No shader named: " + sha);
  79483. }
  79484. }
  79485. if (!hasShaders) {
  79486. onload();
  79487. }
  79488. };
  79489. ;
  79490. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  79491. var hasBuffers = false;
  79492. var processBuffer = function (buf, buffer) {
  79493. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  79494. gltfRuntime.loadedBufferCount++;
  79495. if (bufferView) {
  79496. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  79497. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  79498. }
  79499. gltfRuntime.loadedBufferViews[buf] = bufferView;
  79500. }
  79501. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  79502. onLoad();
  79503. }
  79504. }, function () {
  79505. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  79506. });
  79507. };
  79508. for (var buf in gltfRuntime.buffers) {
  79509. hasBuffers = true;
  79510. var buffer = gltfRuntime.buffers[buf];
  79511. if (buffer) {
  79512. processBuffer.bind(this, buf, buffer)();
  79513. }
  79514. else {
  79515. BABYLON.Tools.Error("No buffer named: " + buf);
  79516. }
  79517. }
  79518. if (!hasBuffers) {
  79519. onLoad();
  79520. }
  79521. };
  79522. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  79523. var currentScene = gltfRuntime.currentScene;
  79524. if (currentScene) {
  79525. // Only one scene even if multiple scenes are defined
  79526. for (var i = 0; i < currentScene.nodes.length; i++) {
  79527. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  79528. }
  79529. }
  79530. else {
  79531. // Load all scenes
  79532. for (var thing in gltfRuntime.scenes) {
  79533. currentScene = gltfRuntime.scenes[thing];
  79534. for (var i = 0; i < currentScene.nodes.length; i++) {
  79535. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  79536. }
  79537. }
  79538. }
  79539. };
  79540. GLTFLoader.Extensions = {};
  79541. return GLTFLoader;
  79542. }());
  79543. GLTF1.GLTFLoader = GLTFLoader;
  79544. ;
  79545. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  79546. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  79547. })(BABYLON || (BABYLON = {}));
  79548. //# sourceMappingURL=babylon.glTFLoader.js.map
  79549. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  79550. var BABYLON;
  79551. (function (BABYLON) {
  79552. var GLTF1;
  79553. (function (GLTF1) {
  79554. /**
  79555. * Utils functions for GLTF
  79556. */
  79557. var GLTFUtils = /** @class */ (function () {
  79558. function GLTFUtils() {
  79559. }
  79560. /**
  79561. * Sets the given "parameter" matrix
  79562. * @param scene: the {BABYLON.Scene} object
  79563. * @param source: the source node where to pick the matrix
  79564. * @param parameter: the GLTF technique parameter
  79565. * @param uniformName: the name of the shader's uniform
  79566. * @param shaderMaterial: the shader material
  79567. */
  79568. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  79569. var mat = null;
  79570. if (parameter.semantic === "MODEL") {
  79571. mat = source.getWorldMatrix();
  79572. }
  79573. else if (parameter.semantic === "PROJECTION") {
  79574. mat = scene.getProjectionMatrix();
  79575. }
  79576. else if (parameter.semantic === "VIEW") {
  79577. mat = scene.getViewMatrix();
  79578. }
  79579. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  79580. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  79581. }
  79582. else if (parameter.semantic === "MODELVIEW") {
  79583. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  79584. }
  79585. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  79586. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  79587. }
  79588. else if (parameter.semantic === "MODELINVERSE") {
  79589. mat = source.getWorldMatrix().invert();
  79590. }
  79591. else if (parameter.semantic === "VIEWINVERSE") {
  79592. mat = scene.getViewMatrix().invert();
  79593. }
  79594. else if (parameter.semantic === "PROJECTIONINVERSE") {
  79595. mat = scene.getProjectionMatrix().invert();
  79596. }
  79597. else if (parameter.semantic === "MODELVIEWINVERSE") {
  79598. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  79599. }
  79600. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  79601. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  79602. }
  79603. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  79604. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  79605. }
  79606. else {
  79607. debugger;
  79608. }
  79609. if (mat) {
  79610. switch (parameter.type) {
  79611. case GLTF1.EParameterType.FLOAT_MAT2:
  79612. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  79613. break;
  79614. case GLTF1.EParameterType.FLOAT_MAT3:
  79615. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  79616. break;
  79617. case GLTF1.EParameterType.FLOAT_MAT4:
  79618. shaderMaterial.setMatrix(uniformName, mat);
  79619. break;
  79620. default: break;
  79621. }
  79622. }
  79623. };
  79624. /**
  79625. * Sets the given "parameter" matrix
  79626. * @param shaderMaterial: the shader material
  79627. * @param uniform: the name of the shader's uniform
  79628. * @param value: the value of the uniform
  79629. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  79630. */
  79631. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  79632. switch (type) {
  79633. case GLTF1.EParameterType.FLOAT:
  79634. shaderMaterial.setFloat(uniform, value);
  79635. return true;
  79636. case GLTF1.EParameterType.FLOAT_VEC2:
  79637. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  79638. return true;
  79639. case GLTF1.EParameterType.FLOAT_VEC3:
  79640. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  79641. return true;
  79642. case GLTF1.EParameterType.FLOAT_VEC4:
  79643. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  79644. return true;
  79645. default: return false;
  79646. }
  79647. };
  79648. /**
  79649. * If the uri is a base64 string
  79650. * @param uri: the uri to test
  79651. */
  79652. GLTFUtils.IsBase64 = function (uri) {
  79653. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  79654. };
  79655. /**
  79656. * Decode the base64 uri
  79657. * @param uri: the uri to decode
  79658. */
  79659. GLTFUtils.DecodeBase64 = function (uri) {
  79660. var decodedString = atob(uri.split(",")[1]);
  79661. var bufferLength = decodedString.length;
  79662. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  79663. for (var i = 0; i < bufferLength; i++) {
  79664. bufferView[i] = decodedString.charCodeAt(i);
  79665. }
  79666. return bufferView.buffer;
  79667. };
  79668. /**
  79669. * Returns the wrap mode of the texture
  79670. * @param mode: the mode value
  79671. */
  79672. GLTFUtils.GetWrapMode = function (mode) {
  79673. switch (mode) {
  79674. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  79675. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  79676. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  79677. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  79678. }
  79679. };
  79680. /**
  79681. * Returns the byte stride giving an accessor
  79682. * @param accessor: the GLTF accessor objet
  79683. */
  79684. GLTFUtils.GetByteStrideFromType = function (accessor) {
  79685. // Needs this function since "byteStride" isn't requiered in glTF format
  79686. var type = accessor.type;
  79687. switch (type) {
  79688. case "VEC2": return 2;
  79689. case "VEC3": return 3;
  79690. case "VEC4": return 4;
  79691. case "MAT2": return 4;
  79692. case "MAT3": return 9;
  79693. case "MAT4": return 16;
  79694. default: return 1;
  79695. }
  79696. };
  79697. /**
  79698. * Returns the texture filter mode giving a mode value
  79699. * @param mode: the filter mode value
  79700. */
  79701. GLTFUtils.GetTextureFilterMode = function (mode) {
  79702. switch (mode) {
  79703. case GLTF1.ETextureFilterType.LINEAR:
  79704. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  79705. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  79706. case GLTF1.ETextureFilterType.NEAREST:
  79707. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  79708. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  79709. }
  79710. };
  79711. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  79712. var byteOffset = bufferView.byteOffset + byteOffset;
  79713. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  79714. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  79715. throw new Error("Buffer access is out of range");
  79716. }
  79717. var buffer = loadedBufferView.buffer;
  79718. byteOffset += loadedBufferView.byteOffset;
  79719. switch (componentType) {
  79720. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  79721. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  79722. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  79723. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  79724. default: return new Float32Array(buffer, byteOffset, byteLength);
  79725. }
  79726. };
  79727. /**
  79728. * Returns a buffer from its accessor
  79729. * @param gltfRuntime: the GLTF runtime
  79730. * @param accessor: the GLTF accessor
  79731. */
  79732. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  79733. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  79734. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  79735. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  79736. };
  79737. /**
  79738. * Decodes a buffer view into a string
  79739. * @param view: the buffer view
  79740. */
  79741. GLTFUtils.DecodeBufferToText = function (view) {
  79742. var result = "";
  79743. var length = view.byteLength;
  79744. for (var i = 0; i < length; ++i) {
  79745. result += String.fromCharCode(view[i]);
  79746. }
  79747. return result;
  79748. };
  79749. /**
  79750. * Returns the default material of gltf. Related to
  79751. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  79752. * @param scene: the Babylon.js scene
  79753. */
  79754. GLTFUtils.GetDefaultMaterial = function (scene) {
  79755. if (!GLTFUtils._DefaultMaterial) {
  79756. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  79757. "precision highp float;",
  79758. "",
  79759. "uniform mat4 worldView;",
  79760. "uniform mat4 projection;",
  79761. "",
  79762. "attribute vec3 position;",
  79763. "",
  79764. "void main(void)",
  79765. "{",
  79766. " gl_Position = projection * worldView * vec4(position, 1.0);",
  79767. "}"
  79768. ].join("\n");
  79769. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  79770. "precision highp float;",
  79771. "",
  79772. "uniform vec4 u_emission;",
  79773. "",
  79774. "void main(void)",
  79775. "{",
  79776. " gl_FragColor = u_emission;",
  79777. "}"
  79778. ].join("\n");
  79779. var shaderPath = {
  79780. vertex: "GLTFDefaultMaterial",
  79781. fragment: "GLTFDefaultMaterial"
  79782. };
  79783. var options = {
  79784. attributes: ["position"],
  79785. uniforms: ["worldView", "projection", "u_emission"],
  79786. samplers: new Array(),
  79787. needAlphaBlending: false
  79788. };
  79789. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  79790. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  79791. }
  79792. return GLTFUtils._DefaultMaterial;
  79793. };
  79794. // The GLTF default material
  79795. GLTFUtils._DefaultMaterial = null;
  79796. return GLTFUtils;
  79797. }());
  79798. GLTF1.GLTFUtils = GLTFUtils;
  79799. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  79800. })(BABYLON || (BABYLON = {}));
  79801. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  79802. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  79803. var BABYLON;
  79804. (function (BABYLON) {
  79805. var GLTF1;
  79806. (function (GLTF1) {
  79807. var GLTFLoaderExtension = /** @class */ (function () {
  79808. function GLTFLoaderExtension(name) {
  79809. this._name = name;
  79810. }
  79811. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  79812. get: function () {
  79813. return this._name;
  79814. },
  79815. enumerable: true,
  79816. configurable: true
  79817. });
  79818. /**
  79819. * Defines an override for loading the runtime
  79820. * Return true to stop further extensions from loading the runtime
  79821. */
  79822. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  79823. return false;
  79824. };
  79825. /**
  79826. * Defines an onverride for creating gltf runtime
  79827. * Return true to stop further extensions from creating the runtime
  79828. */
  79829. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  79830. return false;
  79831. };
  79832. /**
  79833. * Defines an override for loading buffers
  79834. * Return true to stop further extensions from loading this buffer
  79835. */
  79836. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  79837. return false;
  79838. };
  79839. /**
  79840. * Defines an override for loading texture buffers
  79841. * Return true to stop further extensions from loading this texture data
  79842. */
  79843. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  79844. return false;
  79845. };
  79846. /**
  79847. * Defines an override for creating textures
  79848. * Return true to stop further extensions from loading this texture
  79849. */
  79850. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  79851. return false;
  79852. };
  79853. /**
  79854. * Defines an override for loading shader strings
  79855. * Return true to stop further extensions from loading this shader data
  79856. */
  79857. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  79858. return false;
  79859. };
  79860. /**
  79861. * Defines an override for loading materials
  79862. * Return true to stop further extensions from loading this material
  79863. */
  79864. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  79865. return false;
  79866. };
  79867. // ---------
  79868. // Utilities
  79869. // ---------
  79870. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  79871. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  79872. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  79873. }, function () {
  79874. setTimeout(function () {
  79875. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  79876. });
  79877. });
  79878. };
  79879. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  79880. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  79881. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  79882. }, function () {
  79883. setTimeout(function () {
  79884. onSuccess();
  79885. });
  79886. });
  79887. };
  79888. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  79889. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  79890. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  79891. }, function () {
  79892. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  79893. });
  79894. };
  79895. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  79896. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  79897. };
  79898. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  79899. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  79900. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  79901. }, function () {
  79902. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  79903. });
  79904. };
  79905. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  79906. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  79907. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  79908. }, function () {
  79909. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  79910. });
  79911. };
  79912. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  79913. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  79914. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  79915. }, function () {
  79916. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  79917. });
  79918. };
  79919. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  79920. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  79921. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  79922. }, function () {
  79923. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  79924. });
  79925. };
  79926. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  79927. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  79928. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  79929. if (func(loaderExtension)) {
  79930. return;
  79931. }
  79932. }
  79933. defaultFunc();
  79934. };
  79935. return GLTFLoaderExtension;
  79936. }());
  79937. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  79938. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  79939. })(BABYLON || (BABYLON = {}));
  79940. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  79941. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  79942. var BABYLON;
  79943. (function (BABYLON) {
  79944. var GLTF1;
  79945. (function (GLTF1) {
  79946. var BinaryExtensionBufferName = "binary_glTF";
  79947. ;
  79948. ;
  79949. var GLTFBinaryExtension = /** @class */ (function (_super) {
  79950. __extends(GLTFBinaryExtension, _super);
  79951. function GLTFBinaryExtension() {
  79952. return _super.call(this, "KHR_binary_glTF") || this;
  79953. }
  79954. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  79955. var extensionsUsed = data.json.extensionsUsed;
  79956. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  79957. return false;
  79958. }
  79959. this._bin = data.bin;
  79960. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  79961. return true;
  79962. };
  79963. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  79964. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  79965. return false;
  79966. }
  79967. if (id !== BinaryExtensionBufferName) {
  79968. return false;
  79969. }
  79970. onSuccess(this._bin);
  79971. return true;
  79972. };
  79973. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  79974. var texture = gltfRuntime.textures[id];
  79975. var source = gltfRuntime.images[texture.source];
  79976. if (!source.extensions || !(this.name in source.extensions)) {
  79977. return false;
  79978. }
  79979. var sourceExt = source.extensions[this.name];
  79980. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  79981. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  79982. onSuccess(buffer);
  79983. return true;
  79984. };
  79985. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  79986. var shader = gltfRuntime.shaders[id];
  79987. if (!shader.extensions || !(this.name in shader.extensions)) {
  79988. return false;
  79989. }
  79990. var binaryExtensionShader = shader.extensions[this.name];
  79991. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  79992. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  79993. setTimeout(function () {
  79994. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  79995. onSuccess(shaderString);
  79996. });
  79997. return true;
  79998. };
  79999. return GLTFBinaryExtension;
  80000. }(GLTF1.GLTFLoaderExtension));
  80001. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  80002. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  80003. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  80004. })(BABYLON || (BABYLON = {}));
  80005. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  80006. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  80007. var BABYLON;
  80008. (function (BABYLON) {
  80009. var GLTF1;
  80010. (function (GLTF1) {
  80011. ;
  80012. ;
  80013. ;
  80014. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  80015. __extends(GLTFMaterialsCommonExtension, _super);
  80016. function GLTFMaterialsCommonExtension() {
  80017. return _super.call(this, "KHR_materials_common") || this;
  80018. }
  80019. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  80020. if (!gltfRuntime.extensions)
  80021. return false;
  80022. var extension = gltfRuntime.extensions[this.name];
  80023. if (!extension)
  80024. return false;
  80025. // Create lights
  80026. var lights = extension.lights;
  80027. if (lights) {
  80028. for (var thing in lights) {
  80029. var light = lights[thing];
  80030. switch (light.type) {
  80031. case "ambient":
  80032. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  80033. var ambient = light.ambient;
  80034. if (ambient) {
  80035. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  80036. }
  80037. break;
  80038. case "point":
  80039. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  80040. var point = light.point;
  80041. if (point) {
  80042. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  80043. }
  80044. break;
  80045. case "directional":
  80046. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  80047. var directional = light.directional;
  80048. if (directional) {
  80049. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  80050. }
  80051. break;
  80052. case "spot":
  80053. var spot = light.spot;
  80054. if (spot) {
  80055. 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);
  80056. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  80057. }
  80058. break;
  80059. default:
  80060. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  80061. break;
  80062. }
  80063. }
  80064. }
  80065. return false;
  80066. };
  80067. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  80068. var material = gltfRuntime.materials[id];
  80069. if (!material || !material.extensions)
  80070. return false;
  80071. var extension = material.extensions[this.name];
  80072. if (!extension)
  80073. return false;
  80074. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  80075. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  80076. if (extension.technique === "CONSTANT") {
  80077. standardMaterial.disableLighting = true;
  80078. }
  80079. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  80080. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  80081. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  80082. // Ambient
  80083. if (typeof extension.values.ambient === "string") {
  80084. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  80085. }
  80086. else {
  80087. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  80088. }
  80089. // Diffuse
  80090. if (typeof extension.values.diffuse === "string") {
  80091. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  80092. }
  80093. else {
  80094. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  80095. }
  80096. // Emission
  80097. if (typeof extension.values.emission === "string") {
  80098. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  80099. }
  80100. else {
  80101. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  80102. }
  80103. // Specular
  80104. if (typeof extension.values.specular === "string") {
  80105. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  80106. }
  80107. else {
  80108. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  80109. }
  80110. return true;
  80111. };
  80112. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  80113. // Create buffer from texture url
  80114. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  80115. // Create texture from buffer
  80116. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  80117. }, onError);
  80118. };
  80119. return GLTFMaterialsCommonExtension;
  80120. }(GLTF1.GLTFLoaderExtension));
  80121. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  80122. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  80123. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  80124. })(BABYLON || (BABYLON = {}));
  80125. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  80126. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  80127. var BABYLON;
  80128. (function (BABYLON) {
  80129. var GLTF2;
  80130. (function (GLTF2) {
  80131. /**
  80132. * Enums
  80133. */
  80134. var EComponentType;
  80135. (function (EComponentType) {
  80136. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  80137. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  80138. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  80139. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  80140. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  80141. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  80142. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  80143. var EMeshPrimitiveMode;
  80144. (function (EMeshPrimitiveMode) {
  80145. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  80146. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  80147. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  80148. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  80149. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  80150. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  80151. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  80152. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  80153. var ETextureMagFilter;
  80154. (function (ETextureMagFilter) {
  80155. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  80156. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  80157. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  80158. var ETextureMinFilter;
  80159. (function (ETextureMinFilter) {
  80160. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  80161. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  80162. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  80163. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  80164. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  80165. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  80166. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  80167. var ETextureWrapMode;
  80168. (function (ETextureWrapMode) {
  80169. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  80170. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  80171. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  80172. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  80173. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  80174. })(BABYLON || (BABYLON = {}));
  80175. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  80176. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  80177. var BABYLON;
  80178. (function (BABYLON) {
  80179. var GLTF2;
  80180. (function (GLTF2) {
  80181. var GLTFLoaderTracker = /** @class */ (function () {
  80182. function GLTFLoaderTracker(onComplete) {
  80183. this._pendingCount = 0;
  80184. this._callback = onComplete;
  80185. }
  80186. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  80187. this._pendingCount++;
  80188. };
  80189. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  80190. if (--this._pendingCount === 0) {
  80191. this._callback();
  80192. }
  80193. };
  80194. return GLTFLoaderTracker;
  80195. }());
  80196. var GLTFLoader = /** @class */ (function () {
  80197. function GLTFLoader(parent) {
  80198. this._disposed = false;
  80199. this._renderReady = false;
  80200. this._requests = new Array();
  80201. this._renderReadyObservable = new BABYLON.Observable();
  80202. // Count of pending work that needs to complete before the asset is rendered.
  80203. this._renderPendingCount = 0;
  80204. // Count of pending work that needs to complete before the loader is disposed.
  80205. this._loaderPendingCount = 0;
  80206. this._loaderTrackers = new Array();
  80207. this._parent = parent;
  80208. if (!GLTFLoader._progressEventFactory) {
  80209. if (typeof window["ProgressEvent"] === "function") {
  80210. GLTFLoader._progressEventFactory = GLTFLoader._createProgressEventByConstructor;
  80211. }
  80212. else {
  80213. GLTFLoader._progressEventFactory = GLTFLoader._createProgressEventByDocument;
  80214. }
  80215. }
  80216. }
  80217. GLTFLoader.RegisterExtension = function (extension) {
  80218. if (GLTFLoader.Extensions[extension.name]) {
  80219. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  80220. return;
  80221. }
  80222. GLTFLoader.Extensions[extension.name] = extension;
  80223. // Keep the order of registration so that extensions registered first are called first.
  80224. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  80225. };
  80226. GLTFLoader._createProgressEventByConstructor = function (name, data) {
  80227. return new ProgressEvent(name, data);
  80228. };
  80229. GLTFLoader._createProgressEventByDocument = function (name, data) {
  80230. var event = document.createEvent("ProgressEvent");
  80231. event.initProgressEvent(name, false, false, data.lengthComputable, data.loaded, data.total);
  80232. return event;
  80233. };
  80234. GLTFLoader.prototype.dispose = function () {
  80235. if (this._disposed) {
  80236. return;
  80237. }
  80238. this._disposed = true;
  80239. // Abort requests that are not complete
  80240. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  80241. var request = _a[_i];
  80242. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  80243. request.abort();
  80244. }
  80245. }
  80246. // Revoke object urls created during load
  80247. if (this._gltf.textures) {
  80248. for (var _b = 0, _c = this._gltf.textures; _b < _c.length; _b++) {
  80249. var texture = _c[_b];
  80250. if (texture.url) {
  80251. URL.revokeObjectURL(texture.url);
  80252. }
  80253. }
  80254. }
  80255. };
  80256. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  80257. var _this = this;
  80258. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  80259. onSuccess(_this._getMeshes(), [], _this._getSkeletons());
  80260. }, onProgress, onError);
  80261. };
  80262. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  80263. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  80264. };
  80265. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  80266. var _this = this;
  80267. this._tryCatchOnError(function () {
  80268. _this._loadData(data);
  80269. _this._babylonScene = scene;
  80270. _this._rootUrl = rootUrl;
  80271. _this._successCallback = onSuccess;
  80272. _this._progressCallback = onProgress;
  80273. _this._errorCallback = onError;
  80274. _this._addPendingData(_this);
  80275. _this._loadDefaultScene(nodeNames);
  80276. _this._loadAnimations();
  80277. _this._removePendingData(_this);
  80278. });
  80279. };
  80280. GLTFLoader.prototype._onProgress = function () {
  80281. if (!this._progressCallback) {
  80282. return;
  80283. }
  80284. var loaded = 0;
  80285. var total = 0;
  80286. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  80287. var request = _a[_i];
  80288. if (!request._loaded || !request._total) {
  80289. return;
  80290. }
  80291. loaded += request._loaded;
  80292. total += request._total;
  80293. }
  80294. this._progressCallback(GLTFLoader._progressEventFactory("GLTFLoaderProgress", {
  80295. lengthComputable: true,
  80296. loaded: loaded,
  80297. total: total
  80298. }));
  80299. };
  80300. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  80301. if (this._renderReady) {
  80302. func();
  80303. }
  80304. else {
  80305. this._renderReadyObservable.add(func);
  80306. }
  80307. };
  80308. GLTFLoader.prototype._onRenderReady = function () {
  80309. this._rootNode.babylonMesh.setEnabled(true);
  80310. this._startAnimations();
  80311. this._successCallback();
  80312. this._renderReadyObservable.notifyObservers(this);
  80313. };
  80314. GLTFLoader.prototype._onComplete = function () {
  80315. if (this._parent.onComplete) {
  80316. this._parent.onComplete();
  80317. }
  80318. this.dispose();
  80319. };
  80320. GLTFLoader.prototype._loadData = function (data) {
  80321. this._gltf = data.json;
  80322. // Assign the index of each object for convinience.
  80323. GLTFLoader._AssignIndices(this._gltf.accessors);
  80324. GLTFLoader._AssignIndices(this._gltf.animations);
  80325. GLTFLoader._AssignIndices(this._gltf.buffers);
  80326. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  80327. GLTFLoader._AssignIndices(this._gltf.images);
  80328. GLTFLoader._AssignIndices(this._gltf.materials);
  80329. GLTFLoader._AssignIndices(this._gltf.meshes);
  80330. GLTFLoader._AssignIndices(this._gltf.nodes);
  80331. GLTFLoader._AssignIndices(this._gltf.scenes);
  80332. GLTFLoader._AssignIndices(this._gltf.skins);
  80333. GLTFLoader._AssignIndices(this._gltf.textures);
  80334. if (data.bin) {
  80335. var buffers = this._gltf.buffers;
  80336. if (buffers && buffers[0] && !buffers[0].uri) {
  80337. var binaryBuffer = buffers[0];
  80338. if (binaryBuffer.byteLength != data.bin.byteLength) {
  80339. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  80340. }
  80341. binaryBuffer.loadedData = data.bin;
  80342. }
  80343. else {
  80344. BABYLON.Tools.Warn("Unexpected BIN chunk");
  80345. }
  80346. }
  80347. };
  80348. GLTFLoader.prototype._getMeshes = function () {
  80349. var meshes = new Array();
  80350. // Root mesh is always first.
  80351. meshes.push(this._rootNode.babylonMesh);
  80352. var nodes = this._gltf.nodes;
  80353. if (nodes) {
  80354. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  80355. var node = nodes_1[_i];
  80356. if (node.babylonMesh) {
  80357. meshes.push(node.babylonMesh);
  80358. }
  80359. }
  80360. }
  80361. return meshes;
  80362. };
  80363. GLTFLoader.prototype._getSkeletons = function () {
  80364. var skeletons = new Array();
  80365. var skins = this._gltf.skins;
  80366. if (skins) {
  80367. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  80368. var skin = skins_1[_i];
  80369. if (skin.babylonSkeleton) {
  80370. skeletons.push(skin.babylonSkeleton);
  80371. }
  80372. }
  80373. }
  80374. return skeletons;
  80375. };
  80376. GLTFLoader.prototype._getAnimationTargets = function () {
  80377. var targets = new Array();
  80378. var animations = this._gltf.animations;
  80379. if (animations) {
  80380. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  80381. var animation = animations_1[_i];
  80382. targets.push.apply(targets, animation.targets);
  80383. }
  80384. }
  80385. return targets;
  80386. };
  80387. GLTFLoader.prototype._startAnimations = function () {
  80388. for (var _i = 0, _a = this._getAnimationTargets(); _i < _a.length; _i++) {
  80389. var target = _a[_i];
  80390. this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true);
  80391. }
  80392. };
  80393. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  80394. var scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  80395. if (!scene) {
  80396. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  80397. }
  80398. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  80399. };
  80400. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  80401. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  80402. switch (this._parent.coordinateSystemMode) {
  80403. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  80404. if (!this._babylonScene.useRightHandedSystem) {
  80405. this._rootNode.babylonMesh.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  80406. this._rootNode.babylonMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  80407. }
  80408. break;
  80409. }
  80410. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH: {
  80411. // do nothing
  80412. break;
  80413. }
  80414. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  80415. this._babylonScene.useRightHandedSystem = true;
  80416. break;
  80417. }
  80418. default: {
  80419. BABYLON.Tools.Error("Invalid coordinate system mode " + this._parent.coordinateSystemMode);
  80420. return;
  80421. }
  80422. }
  80423. if (this._parent.onMeshLoaded) {
  80424. this._parent.onMeshLoaded(this._rootNode.babylonMesh);
  80425. }
  80426. var nodeIndices = scene.nodes;
  80427. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  80428. node.parent = parentNode;
  80429. return true;
  80430. }, this._rootNode);
  80431. if (nodeNames) {
  80432. if (!(nodeNames instanceof Array)) {
  80433. nodeNames = [nodeNames];
  80434. }
  80435. var filteredNodeIndices_1 = new Array();
  80436. this._traverseNodes(context, nodeIndices, function (node) {
  80437. if (nodeNames.indexOf(node.name) !== -1) {
  80438. filteredNodeIndices_1.push(node.index);
  80439. return false;
  80440. }
  80441. return true;
  80442. }, this._rootNode);
  80443. nodeIndices = filteredNodeIndices_1;
  80444. }
  80445. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  80446. var index = nodeIndices_1[_i];
  80447. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  80448. if (!node) {
  80449. throw new Error(context + ": Failed to find node " + index);
  80450. }
  80451. this._loadNode("#/nodes/" + index, node);
  80452. }
  80453. // Disable the root mesh until the asset is ready to render.
  80454. this._rootNode.babylonMesh.setEnabled(false);
  80455. };
  80456. GLTFLoader.prototype._loadNode = function (context, node) {
  80457. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  80458. return;
  80459. }
  80460. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  80461. node.babylonMesh.hasVertexAlpha = true;
  80462. this._loadTransform(node);
  80463. if (node.mesh != null) {
  80464. var mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  80465. if (!mesh) {
  80466. throw new Error(context + ": Failed to find mesh " + node.mesh);
  80467. }
  80468. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  80469. }
  80470. node.babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  80471. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  80472. node.babylonAnimationTargets.push(node.babylonMesh);
  80473. if (node.skin != null) {
  80474. var skin = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  80475. if (!skin) {
  80476. throw new Error(context + ": Failed to find skin " + node.skin);
  80477. }
  80478. node.babylonMesh.skeleton = this._loadSkin("#/skins/" + node.skin, skin);
  80479. }
  80480. if (node.camera != null) {
  80481. // TODO: handle cameras
  80482. }
  80483. if (node.children) {
  80484. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  80485. var index = _a[_i];
  80486. var childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  80487. if (!childNode) {
  80488. throw new Error(context + ": Failed to find child node " + index);
  80489. }
  80490. this._loadNode("#/nodes/" + index, childNode);
  80491. }
  80492. }
  80493. if (this._parent.onMeshLoaded) {
  80494. this._parent.onMeshLoaded(node.babylonMesh);
  80495. }
  80496. };
  80497. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  80498. var _this = this;
  80499. var primitives = mesh.primitives;
  80500. if (!primitives || primitives.length === 0) {
  80501. throw new Error(context + ": Primitives are missing");
  80502. }
  80503. this._createMorphTargets(context, node, mesh);
  80504. this._loadAllVertexDataAsync(context, mesh, function () {
  80505. _this._loadMorphTargets(context, node, mesh);
  80506. var vertexData = new BABYLON.VertexData();
  80507. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  80508. var primitive = primitives_1[_i];
  80509. vertexData.merge(primitive.vertexData);
  80510. }
  80511. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  80512. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  80513. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  80514. node.babylonMesh.subMeshes = [];
  80515. var verticesStart = 0;
  80516. var indicesStart = 0;
  80517. for (var index = 0; index < primitives.length; index++) {
  80518. var vertexData_1 = primitives[index].vertexData;
  80519. var verticesCount = vertexData_1.positions.length;
  80520. var indicesCount = vertexData_1.indices.length;
  80521. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  80522. verticesStart += verticesCount;
  80523. indicesStart += indicesCount;
  80524. }
  80525. ;
  80526. });
  80527. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  80528. node.babylonMesh.material = multiMaterial;
  80529. var subMaterials = multiMaterial.subMaterials;
  80530. var _loop_1 = function (index) {
  80531. var primitive = primitives[index];
  80532. if (primitive.material == null) {
  80533. subMaterials[index] = this_1._getDefaultMaterial();
  80534. }
  80535. else {
  80536. var material = GLTFLoader._GetProperty(this_1._gltf.materials, primitive.material);
  80537. if (!material) {
  80538. throw new Error(context + ": Failed to find material " + primitive.material);
  80539. }
  80540. this_1._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  80541. if (isNew && _this._parent.onMaterialLoaded) {
  80542. _this._parent.onMaterialLoaded(babylonMaterial);
  80543. }
  80544. subMaterials[index] = babylonMaterial;
  80545. });
  80546. }
  80547. };
  80548. var this_1 = this;
  80549. for (var index = 0; index < primitives.length; index++) {
  80550. _loop_1(index);
  80551. }
  80552. ;
  80553. };
  80554. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  80555. var primitives = mesh.primitives;
  80556. var numRemainingPrimitives = primitives.length;
  80557. var _loop_2 = function (index) {
  80558. var primitive = primitives[index];
  80559. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  80560. primitive.vertexData = vertexData;
  80561. if (--numRemainingPrimitives === 0) {
  80562. onSuccess();
  80563. }
  80564. });
  80565. };
  80566. var this_2 = this;
  80567. for (var index = 0; index < primitives.length; index++) {
  80568. _loop_2(index);
  80569. }
  80570. };
  80571. /**
  80572. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  80573. * @param {ArrayBufferView} data
  80574. * @param {IGLTFAccessor} accessor
  80575. */
  80576. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  80577. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  80578. return data;
  80579. }
  80580. var buffer = data;
  80581. var factor = 1;
  80582. switch (accessor.componentType) {
  80583. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  80584. factor = 1 / 255;
  80585. break;
  80586. }
  80587. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  80588. factor = 1 / 65535;
  80589. break;
  80590. }
  80591. default: {
  80592. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  80593. }
  80594. }
  80595. var result = new Float32Array(accessor.count * 2);
  80596. for (var i = 0; i < result.length; ++i) {
  80597. result[i] = buffer[i] * factor;
  80598. }
  80599. return result;
  80600. };
  80601. /**
  80602. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  80603. * @param {ArrayBufferView} data
  80604. * @param {IGLTFAccessor} accessor
  80605. */
  80606. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  80607. var colorComponentCount = GLTFLoader._GetNumComponents(accessor.type);
  80608. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  80609. return data;
  80610. }
  80611. var buffer = data;
  80612. var factor = 1;
  80613. switch (accessor.componentType) {
  80614. case GLTF2.EComponentType.FLOAT: {
  80615. factor = 1;
  80616. break;
  80617. }
  80618. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  80619. factor = 1 / 255;
  80620. break;
  80621. }
  80622. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  80623. factor = 1 / 65535;
  80624. break;
  80625. }
  80626. default: {
  80627. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  80628. }
  80629. }
  80630. var result = new Float32Array(accessor.count * 4);
  80631. if (colorComponentCount === 4) {
  80632. for (var i = 0; i < result.length; ++i) {
  80633. result[i] = buffer[i] * factor;
  80634. }
  80635. }
  80636. else {
  80637. var offset = 0;
  80638. for (var i = 0; i < result.length; ++i) {
  80639. if ((i + 1) % 4 === 0) {
  80640. result[i] = 1;
  80641. }
  80642. else {
  80643. result[i] = buffer[offset++] * factor;
  80644. }
  80645. }
  80646. }
  80647. return result;
  80648. };
  80649. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  80650. var _this = this;
  80651. var attributes = primitive.attributes;
  80652. if (!attributes) {
  80653. throw new Error(context + ": Attributes are missing");
  80654. }
  80655. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  80656. // TODO: handle other primitive modes
  80657. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  80658. }
  80659. var vertexData = new BABYLON.VertexData();
  80660. var numRemainingAttributes = Object.keys(attributes).length;
  80661. var _loop_3 = function (attribute) {
  80662. var accessor = GLTFLoader._GetProperty(this_3._gltf.accessors, attributes[attribute]);
  80663. if (!accessor) {
  80664. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  80665. }
  80666. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  80667. switch (attribute) {
  80668. case "POSITION": {
  80669. vertexData.positions = data;
  80670. break;
  80671. }
  80672. case "NORMAL": {
  80673. vertexData.normals = data;
  80674. break;
  80675. }
  80676. case "TANGENT": {
  80677. vertexData.tangents = data;
  80678. break;
  80679. }
  80680. case "TEXCOORD_0": {
  80681. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  80682. break;
  80683. }
  80684. case "TEXCOORD_1": {
  80685. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  80686. break;
  80687. }
  80688. case "JOINTS_0": {
  80689. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  80690. break;
  80691. }
  80692. case "WEIGHTS_0": {
  80693. //TODO: need to add support for normalized weights.
  80694. vertexData.matricesWeights = data;
  80695. break;
  80696. }
  80697. case "COLOR_0": {
  80698. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  80699. break;
  80700. }
  80701. default: {
  80702. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  80703. break;
  80704. }
  80705. }
  80706. if (--numRemainingAttributes === 0) {
  80707. if (primitive.indices == null) {
  80708. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  80709. for (var i = 0; i < vertexData.indices.length; i++) {
  80710. vertexData.indices[i] = i;
  80711. }
  80712. onSuccess(vertexData);
  80713. }
  80714. else {
  80715. var indicesAccessor = GLTFLoader._GetProperty(_this._gltf.accessors, primitive.indices);
  80716. if (!indicesAccessor) {
  80717. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  80718. }
  80719. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  80720. vertexData.indices = data;
  80721. onSuccess(vertexData);
  80722. });
  80723. }
  80724. }
  80725. });
  80726. };
  80727. var this_3 = this;
  80728. for (var attribute in attributes) {
  80729. _loop_3(attribute);
  80730. }
  80731. };
  80732. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  80733. var primitives = mesh.primitives;
  80734. var targets = primitives[0].targets;
  80735. if (!targets) {
  80736. return;
  80737. }
  80738. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  80739. var primitive = primitives_2[_i];
  80740. if (!primitive.targets || primitive.targets.length != targets.length) {
  80741. throw new Error(context + ": All primitives are required to list the same number of targets");
  80742. }
  80743. }
  80744. var morphTargetManager = new BABYLON.MorphTargetManager();
  80745. node.babylonMesh.morphTargetManager = morphTargetManager;
  80746. for (var index = 0; index < targets.length; index++) {
  80747. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  80748. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  80749. }
  80750. };
  80751. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  80752. var morphTargetManager = node.babylonMesh.morphTargetManager;
  80753. if (!morphTargetManager) {
  80754. return;
  80755. }
  80756. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  80757. var numTargets = morphTargetManager.numTargets;
  80758. for (var index = 0; index < numTargets; index++) {
  80759. var vertexData = new BABYLON.VertexData();
  80760. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  80761. var primitive = _a[_i];
  80762. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  80763. }
  80764. if (!vertexData.positions) {
  80765. throw new Error(context + ": Positions are missing");
  80766. }
  80767. var target = morphTargetManager.getTarget(index);
  80768. target.setPositions(vertexData.positions);
  80769. target.setNormals(vertexData.normals);
  80770. target.setTangents(vertexData.tangents);
  80771. }
  80772. });
  80773. };
  80774. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  80775. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  80776. var _loop_4 = function (primitive) {
  80777. var targets = primitive.targets;
  80778. primitive.targetsVertexData = new Array(targets.length);
  80779. var _loop_5 = function (index) {
  80780. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  80781. primitive.targetsVertexData[index] = vertexData;
  80782. if (--numRemainingTargets === 0) {
  80783. onSuccess();
  80784. }
  80785. });
  80786. };
  80787. for (var index = 0; index < targets.length; index++) {
  80788. _loop_5(index);
  80789. }
  80790. };
  80791. var this_4 = this;
  80792. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  80793. var primitive = _a[_i];
  80794. _loop_4(primitive);
  80795. }
  80796. };
  80797. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  80798. var targetVertexData = new BABYLON.VertexData();
  80799. var numRemainingAttributes = Object.keys(attributes).length;
  80800. var _loop_6 = function (attribute) {
  80801. var accessor = GLTFLoader._GetProperty(this_5._gltf.accessors, attributes[attribute]);
  80802. if (!accessor) {
  80803. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  80804. }
  80805. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  80806. // glTF stores morph target information as deltas while babylon.js expects the final data.
  80807. // As a result we have to add the original data to the delta to calculate the final data.
  80808. var values = data;
  80809. switch (attribute) {
  80810. case "POSITION": {
  80811. for (var i = 0; i < values.length; i++) {
  80812. values[i] += vertexData.positions[i];
  80813. }
  80814. targetVertexData.positions = values;
  80815. break;
  80816. }
  80817. case "NORMAL": {
  80818. for (var i = 0; i < values.length; i++) {
  80819. values[i] += vertexData.normals[i];
  80820. }
  80821. targetVertexData.normals = values;
  80822. break;
  80823. }
  80824. case "TANGENT": {
  80825. // Tangent data for morph targets is stored as xyz delta.
  80826. // The vertexData.tangent is stored as xyzw.
  80827. // So we need to skip every fourth vertexData.tangent.
  80828. for (var i = 0, j = 0; i < values.length; i++, j++) {
  80829. values[i] += vertexData.tangents[j];
  80830. if ((i + 1) % 3 == 0) {
  80831. j++;
  80832. }
  80833. }
  80834. targetVertexData.tangents = values;
  80835. break;
  80836. }
  80837. default: {
  80838. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  80839. break;
  80840. }
  80841. }
  80842. if (--numRemainingAttributes === 0) {
  80843. onSuccess(targetVertexData);
  80844. }
  80845. });
  80846. };
  80847. var this_5 = this;
  80848. for (var attribute in attributes) {
  80849. _loop_6(attribute);
  80850. }
  80851. };
  80852. GLTFLoader.prototype._loadTransform = function (node) {
  80853. var position = BABYLON.Vector3.Zero();
  80854. var rotation = BABYLON.Quaternion.Identity();
  80855. var scaling = BABYLON.Vector3.One();
  80856. if (node.matrix) {
  80857. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  80858. matrix.decompose(scaling, rotation, position);
  80859. }
  80860. else {
  80861. if (node.translation)
  80862. position = BABYLON.Vector3.FromArray(node.translation);
  80863. if (node.rotation)
  80864. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  80865. if (node.scale)
  80866. scaling = BABYLON.Vector3.FromArray(node.scale);
  80867. }
  80868. node.babylonMesh.position = position;
  80869. node.babylonMesh.rotationQuaternion = rotation;
  80870. node.babylonMesh.scaling = scaling;
  80871. };
  80872. GLTFLoader.prototype._loadSkin = function (context, skin) {
  80873. var _this = this;
  80874. var skeletonId = "skeleton" + skin.index;
  80875. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  80876. if (skin.inverseBindMatrices == null) {
  80877. this._loadBones(context, skin, null);
  80878. }
  80879. else {
  80880. var accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  80881. if (!accessor) {
  80882. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  80883. }
  80884. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  80885. _this._loadBones(context, skin, data);
  80886. });
  80887. }
  80888. return skin.babylonSkeleton;
  80889. };
  80890. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  80891. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  80892. node.babylonBones = node.babylonBones || {};
  80893. node.babylonBones[skin.index] = babylonBone;
  80894. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  80895. node.babylonAnimationTargets.push(babylonBone);
  80896. return babylonBone;
  80897. };
  80898. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  80899. var babylonBones = {};
  80900. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  80901. var index = _a[_i];
  80902. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  80903. if (!node) {
  80904. throw new Error(context + ": Failed to find joint " + index);
  80905. }
  80906. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  80907. }
  80908. };
  80909. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  80910. var babylonBone = babylonBones[node.index];
  80911. if (babylonBone) {
  80912. return babylonBone;
  80913. }
  80914. var boneIndex = skin.joints.indexOf(node.index);
  80915. var baseMatrix = BABYLON.Matrix.Identity();
  80916. if (inverseBindMatrixData && boneIndex !== -1) {
  80917. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  80918. baseMatrix.invertToRef(baseMatrix);
  80919. }
  80920. var babylonParentBone = null;
  80921. if (node.index !== skin.skeleton && node.parent && node.parent !== this._rootNode) {
  80922. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  80923. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  80924. }
  80925. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  80926. babylonBones[node.index] = babylonBone;
  80927. return babylonBone;
  80928. };
  80929. GLTFLoader.prototype._getNodeMatrix = function (node) {
  80930. return node.matrix ?
  80931. BABYLON.Matrix.FromArray(node.matrix) :
  80932. 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());
  80933. };
  80934. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  80935. if (parentNode === void 0) { parentNode = null; }
  80936. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  80937. var index = indices_1[_i];
  80938. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  80939. if (!node) {
  80940. throw new Error(context + ": Failed to find node " + index);
  80941. }
  80942. this._traverseNode(context, node, action, parentNode);
  80943. }
  80944. };
  80945. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  80946. if (parentNode === void 0) { parentNode = null; }
  80947. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  80948. return;
  80949. }
  80950. if (!action(node, parentNode)) {
  80951. return;
  80952. }
  80953. if (node.children) {
  80954. this._traverseNodes(context, node.children, action, node);
  80955. }
  80956. };
  80957. GLTFLoader.prototype._loadAnimations = function () {
  80958. var animations = this._gltf.animations;
  80959. if (!animations) {
  80960. return;
  80961. }
  80962. for (var index = 0; index < animations.length; index++) {
  80963. var animation = animations[index];
  80964. this._loadAnimation("#/animations/" + index, animation);
  80965. }
  80966. };
  80967. GLTFLoader.prototype._loadAnimation = function (context, animation) {
  80968. animation.targets = [];
  80969. for (var index = 0; index < animation.channels.length; index++) {
  80970. var channel = GLTFLoader._GetProperty(animation.channels, index);
  80971. if (!channel) {
  80972. throw new Error(context + ": Failed to find channel " + index);
  80973. }
  80974. var sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  80975. if (!sampler) {
  80976. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  80977. }
  80978. this._loadAnimationChannel(animation, context + "/channels/" + index, channel, context + "/samplers/" + channel.sampler, sampler);
  80979. }
  80980. };
  80981. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  80982. var targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  80983. if (!targetNode) {
  80984. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  80985. }
  80986. var targetPath;
  80987. var animationType;
  80988. switch (channel.target.path) {
  80989. case "translation": {
  80990. targetPath = "position";
  80991. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  80992. break;
  80993. }
  80994. case "rotation": {
  80995. targetPath = "rotationQuaternion";
  80996. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  80997. break;
  80998. }
  80999. case "scale": {
  81000. targetPath = "scaling";
  81001. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  81002. break;
  81003. }
  81004. case "weights": {
  81005. targetPath = "influence";
  81006. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  81007. break;
  81008. }
  81009. default: {
  81010. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  81011. }
  81012. }
  81013. var inputData;
  81014. var outputData;
  81015. var checkSuccess = function () {
  81016. if (!inputData || !outputData) {
  81017. return;
  81018. }
  81019. var outputBufferOffset = 0;
  81020. var getNextOutputValue;
  81021. switch (targetPath) {
  81022. case "position": {
  81023. getNextOutputValue = function () {
  81024. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  81025. outputBufferOffset += 3;
  81026. return value;
  81027. };
  81028. break;
  81029. }
  81030. case "rotationQuaternion": {
  81031. getNextOutputValue = function () {
  81032. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  81033. outputBufferOffset += 4;
  81034. return value;
  81035. };
  81036. break;
  81037. }
  81038. case "scaling": {
  81039. getNextOutputValue = function () {
  81040. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  81041. outputBufferOffset += 3;
  81042. return value;
  81043. };
  81044. break;
  81045. }
  81046. case "influence": {
  81047. getNextOutputValue = function () {
  81048. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  81049. var value = new Array(numTargets);
  81050. for (var i = 0; i < numTargets; i++) {
  81051. value[i] = outputData[outputBufferOffset++];
  81052. }
  81053. return value;
  81054. };
  81055. break;
  81056. }
  81057. }
  81058. var getNextKey;
  81059. switch (sampler.interpolation) {
  81060. case "LINEAR": {
  81061. getNextKey = function (frameIndex) { return ({
  81062. frame: inputData[frameIndex],
  81063. value: getNextOutputValue()
  81064. }); };
  81065. break;
  81066. }
  81067. case "CUBICSPLINE": {
  81068. getNextKey = function (frameIndex) { return ({
  81069. frame: inputData[frameIndex],
  81070. inTangent: getNextOutputValue(),
  81071. value: getNextOutputValue(),
  81072. outTangent: getNextOutputValue()
  81073. }); };
  81074. break;
  81075. }
  81076. default: {
  81077. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  81078. }
  81079. }
  81080. ;
  81081. var keys = new Array(inputData.length);
  81082. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  81083. keys[frameIndex] = getNextKey(frameIndex);
  81084. }
  81085. if (targetPath === "influence") {
  81086. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  81087. var _loop_7 = function (targetIndex) {
  81088. var morphTarget = morphTargetManager.getTarget(targetIndex);
  81089. var animationName = (animation.name || "anim" + animation.index) + "_" + targetIndex;
  81090. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  81091. babylonAnimation.setKeys(keys.map(function (key) { return ({
  81092. frame: key.frame,
  81093. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  81094. value: key.value[targetIndex],
  81095. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  81096. }); }));
  81097. morphTarget.animations.push(babylonAnimation);
  81098. animation.targets.push(morphTarget);
  81099. };
  81100. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  81101. _loop_7(targetIndex);
  81102. }
  81103. }
  81104. else {
  81105. var animationName = animation.name || "anim" + animation.index;
  81106. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  81107. babylonAnimation.setKeys(keys);
  81108. if (targetNode.babylonAnimationTargets) {
  81109. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  81110. var target = _a[_i];
  81111. target.animations.push(babylonAnimation.clone());
  81112. animation.targets.push(target);
  81113. }
  81114. }
  81115. }
  81116. };
  81117. var inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  81118. if (!inputAccessor) {
  81119. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  81120. }
  81121. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  81122. inputData = data;
  81123. checkSuccess();
  81124. });
  81125. var outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  81126. if (!outputAccessor) {
  81127. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  81128. }
  81129. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  81130. outputData = data;
  81131. checkSuccess();
  81132. });
  81133. };
  81134. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  81135. var _this = this;
  81136. this._addPendingData(buffer);
  81137. if (buffer.loadedData) {
  81138. onSuccess(buffer.loadedData);
  81139. this._removePendingData(buffer);
  81140. }
  81141. else if (buffer.loadedObservable) {
  81142. buffer.loadedObservable.add(function (buffer) {
  81143. onSuccess(buffer.loadedData);
  81144. _this._removePendingData(buffer);
  81145. });
  81146. }
  81147. else {
  81148. if (!buffer.uri) {
  81149. throw new Error(context + ": Uri is missing");
  81150. }
  81151. buffer.loadedObservable = new BABYLON.Observable();
  81152. buffer.loadedObservable.add(function (buffer) {
  81153. onSuccess(buffer.loadedData);
  81154. _this._removePendingData(buffer);
  81155. });
  81156. this._loadUriAsync(context, buffer.uri, function (data) {
  81157. buffer.loadedData = data;
  81158. buffer.loadedObservable.notifyObservers(buffer);
  81159. buffer.loadedObservable = undefined;
  81160. });
  81161. }
  81162. };
  81163. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  81164. var buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  81165. if (!buffer) {
  81166. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  81167. }
  81168. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  81169. var data;
  81170. try {
  81171. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  81172. }
  81173. catch (e) {
  81174. throw new Error(context + ": " + e.message);
  81175. }
  81176. onSuccess(data);
  81177. });
  81178. };
  81179. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  81180. var _this = this;
  81181. if (accessor.sparse) {
  81182. throw new Error(context + ": Sparse accessors are not currently supported");
  81183. }
  81184. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  81185. if (!bufferView) {
  81186. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  81187. }
  81188. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  81189. var numComponents = GLTFLoader._GetNumComponents(accessor.type);
  81190. if (numComponents === 0) {
  81191. throw new Error(context + ": Invalid type " + accessor.type);
  81192. }
  81193. var data;
  81194. var byteOffset = accessor.byteOffset || 0;
  81195. var byteStride = bufferView.byteStride;
  81196. try {
  81197. switch (accessor.componentType) {
  81198. case GLTF2.EComponentType.BYTE: {
  81199. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  81200. break;
  81201. }
  81202. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  81203. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  81204. break;
  81205. }
  81206. case GLTF2.EComponentType.SHORT: {
  81207. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  81208. break;
  81209. }
  81210. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  81211. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  81212. break;
  81213. }
  81214. case GLTF2.EComponentType.UNSIGNED_INT: {
  81215. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  81216. break;
  81217. }
  81218. case GLTF2.EComponentType.FLOAT: {
  81219. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  81220. break;
  81221. }
  81222. default: {
  81223. throw new Error(context + ": Invalid component type " + accessor.componentType);
  81224. }
  81225. }
  81226. }
  81227. catch (e) {
  81228. throw new Error(context + ": " + e);
  81229. }
  81230. onSuccess(data);
  81231. });
  81232. };
  81233. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  81234. byteOffset += data.byteOffset;
  81235. var targetLength = count * numComponents;
  81236. if (byteStride == null || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  81237. return new typedArray(data.buffer, byteOffset, targetLength);
  81238. }
  81239. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  81240. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  81241. var targetBuffer = new typedArray(targetLength);
  81242. var sourceIndex = 0;
  81243. var targetIndex = 0;
  81244. while (targetIndex < targetLength) {
  81245. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  81246. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  81247. targetIndex++;
  81248. }
  81249. sourceIndex += elementStride;
  81250. }
  81251. return targetBuffer;
  81252. };
  81253. GLTFLoader.prototype._addPendingData = function (data) {
  81254. if (!this._renderReady) {
  81255. this._renderPendingCount++;
  81256. }
  81257. this._addLoaderPendingData(data);
  81258. };
  81259. GLTFLoader.prototype._removePendingData = function (data) {
  81260. var _this = this;
  81261. if (!this._renderReady) {
  81262. if (--this._renderPendingCount === 0) {
  81263. this._addLoaderPendingData(this);
  81264. this._compileMaterialsAsync(function () {
  81265. _this._compileShadowGeneratorsAsync(function () {
  81266. _this._removeLoaderPendingData(_this);
  81267. _this._renderReady = true;
  81268. _this._onRenderReady();
  81269. });
  81270. });
  81271. }
  81272. }
  81273. this._removeLoaderPendingData(data);
  81274. };
  81275. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  81276. this._loaderPendingCount++;
  81277. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  81278. var tracker = _a[_i];
  81279. tracker._addPendingData(data);
  81280. }
  81281. };
  81282. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  81283. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  81284. var tracker = _a[_i];
  81285. tracker._removePendingData(data);
  81286. }
  81287. if (--this._loaderPendingCount === 0) {
  81288. this._onComplete();
  81289. }
  81290. };
  81291. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  81292. var _this = this;
  81293. var tracker = new GLTFLoaderTracker(function () {
  81294. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  81295. onComplete();
  81296. });
  81297. this._loaderTrackers.push(tracker);
  81298. this._addLoaderPendingData(tracker);
  81299. action();
  81300. this._removeLoaderPendingData(tracker);
  81301. };
  81302. GLTFLoader.prototype._getDefaultMaterial = function () {
  81303. if (!this._defaultMaterial) {
  81304. var id = "__gltf_default";
  81305. var material = this._babylonScene.getMaterialByName(id);
  81306. if (!material) {
  81307. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  81308. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  81309. material.metallic = 1;
  81310. material.roughness = 1;
  81311. }
  81312. this._defaultMaterial = material;
  81313. }
  81314. return this._defaultMaterial;
  81315. };
  81316. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  81317. var babylonMaterial = material.babylonMaterial;
  81318. // Ensure metallic workflow
  81319. babylonMaterial.metallic = 1;
  81320. babylonMaterial.roughness = 1;
  81321. var properties = material.pbrMetallicRoughness;
  81322. if (!properties) {
  81323. return;
  81324. }
  81325. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  81326. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  81327. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  81328. if (properties.baseColorTexture) {
  81329. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  81330. if (!texture) {
  81331. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  81332. }
  81333. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  81334. }
  81335. if (properties.metallicRoughnessTexture) {
  81336. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  81337. if (!texture) {
  81338. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  81339. }
  81340. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  81341. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  81342. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  81343. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  81344. }
  81345. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  81346. };
  81347. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  81348. if (material.babylonMaterial) {
  81349. assign(material.babylonMaterial, false);
  81350. return;
  81351. }
  81352. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  81353. return;
  81354. }
  81355. this._createPbrMaterial(material);
  81356. this._loadMaterialBaseProperties(context, material);
  81357. this._loadMaterialMetallicRoughnessProperties(context, material);
  81358. assign(material.babylonMaterial, true);
  81359. };
  81360. GLTFLoader.prototype._createPbrMaterial = function (material) {
  81361. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  81362. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  81363. material.babylonMaterial = babylonMaterial;
  81364. };
  81365. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  81366. var babylonMaterial = material.babylonMaterial;
  81367. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  81368. if (material.doubleSided) {
  81369. babylonMaterial.backFaceCulling = false;
  81370. babylonMaterial.twoSidedLighting = true;
  81371. }
  81372. if (material.normalTexture) {
  81373. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  81374. if (!texture) {
  81375. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  81376. }
  81377. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  81378. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  81379. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  81380. if (material.normalTexture.scale != null) {
  81381. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  81382. }
  81383. }
  81384. if (material.occlusionTexture) {
  81385. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  81386. if (!texture) {
  81387. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  81388. }
  81389. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  81390. babylonMaterial.useAmbientInGrayScale = true;
  81391. if (material.occlusionTexture.strength != null) {
  81392. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  81393. }
  81394. }
  81395. if (material.emissiveTexture) {
  81396. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  81397. if (!texture) {
  81398. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  81399. }
  81400. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  81401. }
  81402. };
  81403. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  81404. var babylonMaterial = material.babylonMaterial;
  81405. var alphaMode = material.alphaMode || "OPAQUE";
  81406. switch (alphaMode) {
  81407. case "OPAQUE": {
  81408. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  81409. break;
  81410. }
  81411. case "MASK": {
  81412. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  81413. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  81414. if (colorFactor) {
  81415. if (colorFactor[3] == 0) {
  81416. babylonMaterial.alphaCutOff = 1;
  81417. }
  81418. else {
  81419. babylonMaterial.alphaCutOff /= colorFactor[3];
  81420. }
  81421. }
  81422. if (babylonMaterial.albedoTexture) {
  81423. babylonMaterial.albedoTexture.hasAlpha = true;
  81424. }
  81425. break;
  81426. }
  81427. case "BLEND": {
  81428. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  81429. if (colorFactor) {
  81430. babylonMaterial.alpha = colorFactor[3];
  81431. }
  81432. if (babylonMaterial.albedoTexture) {
  81433. babylonMaterial.albedoTexture.hasAlpha = true;
  81434. babylonMaterial.useAlphaFromAlbedoTexture = true;
  81435. }
  81436. break;
  81437. }
  81438. default: {
  81439. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  81440. }
  81441. }
  81442. };
  81443. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  81444. var _this = this;
  81445. var sampler = (texture.sampler == null ? {} : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  81446. if (!sampler) {
  81447. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  81448. }
  81449. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  81450. var samplingMode = GLTFLoader._GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  81451. this._addPendingData(texture);
  81452. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  81453. _this._tryCatchOnError(function () {
  81454. _this._removePendingData(texture);
  81455. });
  81456. }, function (message) {
  81457. _this._tryCatchOnError(function () {
  81458. throw new Error(context + ": " + message);
  81459. });
  81460. });
  81461. if (texture.url) {
  81462. babylonTexture.updateURL(texture.url);
  81463. }
  81464. else if (texture.dataReadyObservable) {
  81465. texture.dataReadyObservable.add(function (texture) {
  81466. babylonTexture.updateURL(texture.url);
  81467. });
  81468. }
  81469. else {
  81470. texture.dataReadyObservable = new BABYLON.Observable();
  81471. texture.dataReadyObservable.add(function (texture) {
  81472. babylonTexture.updateURL(texture.url);
  81473. });
  81474. var image_1 = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  81475. if (!image_1) {
  81476. throw new Error(context + ": Failed to find source " + texture.source);
  81477. }
  81478. this._loadImageAsync("#/images/" + image_1.index, image_1, function (data) {
  81479. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  81480. texture.dataReadyObservable.notifyObservers(texture);
  81481. texture.dataReadyObservable = undefined;
  81482. });
  81483. }
  81484. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  81485. babylonTexture.wrapU = GLTFLoader._GetTextureWrapMode(sampler.wrapS);
  81486. babylonTexture.wrapV = GLTFLoader._GetTextureWrapMode(sampler.wrapT);
  81487. babylonTexture.name = texture.name || "texture" + texture.index;
  81488. if (this._parent.onTextureLoaded) {
  81489. this._parent.onTextureLoaded(babylonTexture);
  81490. }
  81491. return babylonTexture;
  81492. };
  81493. GLTFLoader.prototype._loadImageAsync = function (context, image, onSuccess) {
  81494. if (image.uri) {
  81495. this._loadUriAsync(context, image.uri, onSuccess);
  81496. }
  81497. else {
  81498. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  81499. if (!bufferView) {
  81500. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  81501. }
  81502. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  81503. }
  81504. };
  81505. GLTFLoader.prototype._loadUriAsync = function (context, uri, onSuccess) {
  81506. var _this = this;
  81507. if (GLTF2.GLTFUtils.IsBase64(uri)) {
  81508. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(uri)));
  81509. return;
  81510. }
  81511. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  81512. throw new Error(context + ": Uri '" + uri + "' is invalid");
  81513. }
  81514. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  81515. _this._tryCatchOnError(function () {
  81516. onSuccess(new Uint8Array(data));
  81517. });
  81518. }, function (event) {
  81519. _this._tryCatchOnError(function () {
  81520. if (request && !_this._renderReady) {
  81521. request._loaded = event.loaded;
  81522. request._total = event.total;
  81523. _this._onProgress();
  81524. }
  81525. });
  81526. }, this._babylonScene.database, true, function (request) {
  81527. _this._tryCatchOnError(function () {
  81528. throw new Error(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  81529. });
  81530. });
  81531. if (request) {
  81532. request._loaded = null;
  81533. request._total = null;
  81534. this._requests.push(request);
  81535. }
  81536. };
  81537. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  81538. if (this._disposed) {
  81539. return;
  81540. }
  81541. try {
  81542. handler();
  81543. }
  81544. catch (e) {
  81545. BABYLON.Tools.Error("glTF Loader: " + e.message);
  81546. if (this._errorCallback) {
  81547. this._errorCallback(e.message);
  81548. }
  81549. this.dispose();
  81550. }
  81551. };
  81552. GLTFLoader._AssignIndices = function (array) {
  81553. if (array) {
  81554. for (var index = 0; index < array.length; index++) {
  81555. array[index].index = index;
  81556. }
  81557. }
  81558. };
  81559. GLTFLoader._GetProperty = function (array, index) {
  81560. if (!array || index == undefined || !array[index]) {
  81561. return null;
  81562. }
  81563. return array[index];
  81564. };
  81565. GLTFLoader._GetTextureWrapMode = function (mode) {
  81566. // Set defaults if undefined
  81567. mode = mode == undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  81568. switch (mode) {
  81569. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  81570. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  81571. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  81572. default:
  81573. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  81574. return BABYLON.Texture.WRAP_ADDRESSMODE;
  81575. }
  81576. };
  81577. GLTFLoader._GetTextureSamplingMode = function (magFilter, minFilter) {
  81578. // Set defaults if undefined
  81579. magFilter = magFilter == undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  81580. minFilter = minFilter == undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  81581. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  81582. switch (minFilter) {
  81583. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  81584. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  81585. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  81586. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  81587. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  81588. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  81589. default:
  81590. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  81591. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  81592. }
  81593. }
  81594. else {
  81595. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  81596. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  81597. }
  81598. switch (minFilter) {
  81599. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  81600. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  81601. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  81602. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  81603. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  81604. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  81605. default:
  81606. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  81607. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  81608. }
  81609. }
  81610. };
  81611. GLTFLoader._GetNumComponents = function (type) {
  81612. switch (type) {
  81613. case "SCALAR": return 1;
  81614. case "VEC2": return 2;
  81615. case "VEC3": return 3;
  81616. case "VEC4": return 4;
  81617. case "MAT2": return 4;
  81618. case "MAT3": return 9;
  81619. case "MAT4": return 16;
  81620. }
  81621. return 0;
  81622. };
  81623. GLTFLoader.prototype._compileMaterialAsync = function (babylonMaterial, babylonMesh, onSuccess) {
  81624. var _this = this;
  81625. if (!this._parent.compileMaterials) {
  81626. onSuccess();
  81627. return;
  81628. }
  81629. if (this._parent.useClipPlane) {
  81630. babylonMaterial.forceCompilation(babylonMesh, function () {
  81631. babylonMaterial.forceCompilation(babylonMesh, function () {
  81632. _this._tryCatchOnError(onSuccess);
  81633. }, { clipPlane: true });
  81634. });
  81635. }
  81636. else {
  81637. babylonMaterial.forceCompilation(babylonMesh, function () {
  81638. _this._tryCatchOnError(onSuccess);
  81639. });
  81640. }
  81641. };
  81642. GLTFLoader.prototype._compileMaterialsAsync = function (onSuccess) {
  81643. if (!this._parent.compileMaterials || !this._gltf.materials) {
  81644. onSuccess();
  81645. return;
  81646. }
  81647. var meshes = this._getMeshes();
  81648. var remaining = 0;
  81649. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  81650. var mesh = meshes_1[_i];
  81651. if (mesh.material instanceof BABYLON.MultiMaterial) {
  81652. for (var _a = 0, _b = mesh.material.subMaterials; _a < _b.length; _a++) {
  81653. var subMaterial = _b[_a];
  81654. if (subMaterial) {
  81655. remaining++;
  81656. }
  81657. }
  81658. }
  81659. }
  81660. if (remaining === 0) {
  81661. onSuccess();
  81662. return;
  81663. }
  81664. for (var _c = 0, meshes_2 = meshes; _c < meshes_2.length; _c++) {
  81665. var mesh = meshes_2[_c];
  81666. if (mesh.material instanceof BABYLON.MultiMaterial) {
  81667. for (var _d = 0, _e = mesh.material.subMaterials; _d < _e.length; _d++) {
  81668. var subMaterial = _e[_d];
  81669. if (subMaterial) {
  81670. this._compileMaterialAsync(subMaterial, mesh, function () {
  81671. if (--remaining === 0) {
  81672. onSuccess();
  81673. }
  81674. });
  81675. }
  81676. }
  81677. }
  81678. }
  81679. };
  81680. GLTFLoader.prototype._compileShadowGeneratorsAsync = function (onSuccess) {
  81681. var _this = this;
  81682. if (!this._parent.compileShadowGenerators) {
  81683. onSuccess();
  81684. return;
  81685. }
  81686. var lights = this._babylonScene.lights;
  81687. var remaining = 0;
  81688. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  81689. var light = lights_1[_i];
  81690. var generator = light.getShadowGenerator();
  81691. if (generator) {
  81692. remaining++;
  81693. }
  81694. }
  81695. if (remaining === 0) {
  81696. onSuccess();
  81697. return;
  81698. }
  81699. for (var _a = 0, lights_2 = lights; _a < lights_2.length; _a++) {
  81700. var light = lights_2[_a];
  81701. var generator = light.getShadowGenerator();
  81702. if (generator) {
  81703. generator.forceCompilation(function () {
  81704. if (--remaining === 0) {
  81705. _this._tryCatchOnError(onSuccess);
  81706. }
  81707. });
  81708. }
  81709. }
  81710. };
  81711. GLTFLoader.Extensions = {};
  81712. return GLTFLoader;
  81713. }());
  81714. GLTF2.GLTFLoader = GLTFLoader;
  81715. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  81716. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  81717. })(BABYLON || (BABYLON = {}));
  81718. //# sourceMappingURL=babylon.glTFLoader.js.map
  81719. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  81720. var BABYLON;
  81721. (function (BABYLON) {
  81722. var GLTF2;
  81723. (function (GLTF2) {
  81724. /**
  81725. * Utils functions for GLTF
  81726. */
  81727. var GLTFUtils = /** @class */ (function () {
  81728. function GLTFUtils() {
  81729. }
  81730. /**
  81731. * If the uri is a base64 string
  81732. * @param uri: the uri to test
  81733. */
  81734. GLTFUtils.IsBase64 = function (uri) {
  81735. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  81736. };
  81737. /**
  81738. * Decode the base64 uri
  81739. * @param uri: the uri to decode
  81740. */
  81741. GLTFUtils.DecodeBase64 = function (uri) {
  81742. var decodedString = atob(uri.split(",")[1]);
  81743. var bufferLength = decodedString.length;
  81744. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  81745. for (var i = 0; i < bufferLength; i++) {
  81746. bufferView[i] = decodedString.charCodeAt(i);
  81747. }
  81748. return bufferView.buffer;
  81749. };
  81750. GLTFUtils.ValidateUri = function (uri) {
  81751. return (uri.indexOf("..") === -1);
  81752. };
  81753. return GLTFUtils;
  81754. }());
  81755. GLTF2.GLTFUtils = GLTFUtils;
  81756. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  81757. })(BABYLON || (BABYLON = {}));
  81758. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  81759. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  81760. var BABYLON;
  81761. (function (BABYLON) {
  81762. var GLTF2;
  81763. (function (GLTF2) {
  81764. var GLTFLoaderExtension = /** @class */ (function () {
  81765. function GLTFLoaderExtension() {
  81766. this.enabled = true;
  81767. }
  81768. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  81769. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  81770. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  81771. GLTFLoaderExtension.prototype._loadExtension = function (context, property, action) {
  81772. var _this = this;
  81773. if (!property.extensions) {
  81774. return false;
  81775. }
  81776. var extension = property.extensions[this.name];
  81777. if (!extension) {
  81778. return false;
  81779. }
  81780. // Clear out the extension before executing the action to avoid recursing into the same property.
  81781. property.extensions[this.name] = undefined;
  81782. action(context + "extensions/" + this.name, extension, function () {
  81783. // Restore the extension after completing the action.
  81784. property.extensions[_this.name] = extension;
  81785. });
  81786. return true;
  81787. };
  81788. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  81789. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  81790. };
  81791. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  81792. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  81793. };
  81794. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  81795. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  81796. };
  81797. GLTFLoaderExtension._ApplyExtensions = function (action) {
  81798. var extensions = GLTFLoaderExtension._Extensions;
  81799. if (!extensions) {
  81800. return false;
  81801. }
  81802. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  81803. var extension = extensions_1[_i];
  81804. if (extension.enabled && action(extension)) {
  81805. return true;
  81806. }
  81807. }
  81808. return false;
  81809. };
  81810. //
  81811. // Utilities
  81812. //
  81813. GLTFLoaderExtension._Extensions = [];
  81814. return GLTFLoaderExtension;
  81815. }());
  81816. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  81817. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  81818. })(BABYLON || (BABYLON = {}));
  81819. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  81820. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  81821. var BABYLON;
  81822. (function (BABYLON) {
  81823. var GLTF2;
  81824. (function (GLTF2) {
  81825. var Extensions;
  81826. (function (Extensions) {
  81827. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  81828. var MSFTLOD = /** @class */ (function (_super) {
  81829. __extends(MSFTLOD, _super);
  81830. function MSFTLOD() {
  81831. var _this = _super !== null && _super.apply(this, arguments) || this;
  81832. /**
  81833. * Specify the minimal delay between LODs in ms (default = 250)
  81834. */
  81835. _this.Delay = 250;
  81836. return _this;
  81837. }
  81838. Object.defineProperty(MSFTLOD.prototype, "name", {
  81839. get: function () {
  81840. return "MSFT_lod";
  81841. },
  81842. enumerable: true,
  81843. configurable: true
  81844. });
  81845. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  81846. return this._loadExtension(context, node, function (context, extension, onComplete) {
  81847. for (var i = extension.ids.length - 1; i >= 0; i--) {
  81848. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, extension.ids[i]);
  81849. if (!lodNode) {
  81850. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  81851. }
  81852. loader._traverseNode(context, lodNode, action, parentNode);
  81853. }
  81854. loader._traverseNode(context, node, action, parentNode);
  81855. onComplete();
  81856. });
  81857. };
  81858. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  81859. var _this = this;
  81860. return this._loadExtension(context, node, function (context, extension, onComplete) {
  81861. var nodes = [node];
  81862. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  81863. var index = _a[_i];
  81864. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  81865. if (!lodNode) {
  81866. throw new Error(context + ": Failed to find node " + index);
  81867. }
  81868. nodes.push(lodNode);
  81869. }
  81870. loader._addLoaderPendingData(node);
  81871. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  81872. loader._removeLoaderPendingData(node);
  81873. onComplete();
  81874. });
  81875. });
  81876. };
  81877. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  81878. var _this = this;
  81879. loader._whenAction(function () {
  81880. loader._loadNode(context, nodes[index]);
  81881. }, function () {
  81882. if (index !== nodes.length - 1) {
  81883. var previousNode = nodes[index + 1];
  81884. previousNode.babylonMesh.setEnabled(false);
  81885. }
  81886. if (index === 0) {
  81887. onComplete();
  81888. return;
  81889. }
  81890. setTimeout(function () {
  81891. loader._tryCatchOnError(function () {
  81892. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  81893. });
  81894. }, _this.Delay);
  81895. });
  81896. };
  81897. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  81898. var _this = this;
  81899. return this._loadExtension(context, material, function (context, extension, onComplete) {
  81900. var materials = [material];
  81901. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  81902. var index = _a[_i];
  81903. var lodMaterial = GLTF2.GLTFLoader._GetProperty(loader._gltf.materials, index);
  81904. if (!lodMaterial) {
  81905. throw new Error(context + ": Failed to find material " + index);
  81906. }
  81907. materials.push(lodMaterial);
  81908. }
  81909. loader._addLoaderPendingData(material);
  81910. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  81911. loader._removeLoaderPendingData(material);
  81912. onComplete();
  81913. });
  81914. });
  81915. };
  81916. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  81917. var _this = this;
  81918. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  81919. if (index === materials.length - 1) {
  81920. assign(babylonMaterial, isNew);
  81921. // Load the next LOD when the loader is ready to render.
  81922. loader._executeWhenRenderReady(function () {
  81923. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  81924. });
  81925. }
  81926. else {
  81927. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  81928. assign(babylonMaterial, isNew);
  81929. if (index === 0) {
  81930. onComplete();
  81931. }
  81932. else {
  81933. setTimeout(function () {
  81934. loader._tryCatchOnError(function () {
  81935. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  81936. });
  81937. }, _this.Delay);
  81938. }
  81939. });
  81940. }
  81941. });
  81942. };
  81943. return MSFTLOD;
  81944. }(GLTF2.GLTFLoaderExtension));
  81945. Extensions.MSFTLOD = MSFTLOD;
  81946. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  81947. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  81948. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  81949. })(BABYLON || (BABYLON = {}));
  81950. //# sourceMappingURL=MSFT_lod.js.map
  81951. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  81952. var BABYLON;
  81953. (function (BABYLON) {
  81954. var GLTF2;
  81955. (function (GLTF2) {
  81956. var Extensions;
  81957. (function (Extensions) {
  81958. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  81959. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  81960. function KHRMaterialsPbrSpecularGlossiness() {
  81961. return _super !== null && _super.apply(this, arguments) || this;
  81962. }
  81963. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  81964. get: function () {
  81965. return "KHR_materials_pbrSpecularGlossiness";
  81966. },
  81967. enumerable: true,
  81968. configurable: true
  81969. });
  81970. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  81971. var _this = this;
  81972. return this._loadExtension(context, material, function (context, extension, onComplete) {
  81973. loader._createPbrMaterial(material);
  81974. loader._loadMaterialBaseProperties(context, material);
  81975. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  81976. assign(material.babylonMaterial, true);
  81977. onComplete();
  81978. });
  81979. };
  81980. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  81981. var babylonMaterial = material.babylonMaterial;
  81982. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  81983. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  81984. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  81985. if (properties.diffuseTexture) {
  81986. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.diffuseTexture.index);
  81987. if (!texture) {
  81988. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  81989. }
  81990. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  81991. }
  81992. if (properties.specularGlossinessTexture) {
  81993. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.specularGlossinessTexture.index);
  81994. if (!texture) {
  81995. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  81996. }
  81997. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  81998. babylonMaterial.reflectivityTexture.hasAlpha = true;
  81999. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  82000. }
  82001. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  82002. };
  82003. return KHRMaterialsPbrSpecularGlossiness;
  82004. }(GLTF2.GLTFLoaderExtension));
  82005. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  82006. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  82007. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  82008. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  82009. })(BABYLON || (BABYLON = {}));
  82010. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  82011. (function universalModuleDefinition(root, factory) {
  82012. var f = factory();
  82013. if (root && root["BABYLON"]) {
  82014. return;
  82015. }
  82016. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  82017. globalObject["BABYLON"] = f;
  82018. if(typeof exports === 'object' && typeof module === 'object')
  82019. module.exports = f;
  82020. else if(typeof define === 'function' && define.amd)
  82021. define(["BABYLON"], factory);
  82022. else if(typeof exports === 'object')
  82023. exports["BABYLON"] = f;
  82024. else {
  82025. root["BABYLON"] = f;
  82026. }
  82027. })(this, function() {
  82028. return BABYLON;
  82029. });